c++ - 这可能会导致无限循环吗?

标签 c++ recursion constants const-method

为了定义函数的第二个 const 版本,这样做是否保证安全?看起来它会无限递归,因为我想返回 const 但我要调用的另一个函数是非常量。

它适用于 g++,但我担心这不安全。

#include <iostream>

using namespace std;

class test {
public:
   int* doSomething(int a) {
      int* someInt = new int(a);

      return someInt;
   }

   const int* doSomething(int a) const {
      return doSomething(a);
   }
};

int main() {
   test a;

   cout << *a.doSomething(12345) << endl;

   return 1;
}

最佳答案

不完全是:正如@Pete Becker 在评论中指出的那样,如果您调用了 const 版本, 递归:

class test {
public:
   int* doSomething(int a) {
      int* someInt = new int;
      *someInt = a;
      return someInt;
   }

   const int* doSomething(int a) const {
      return doSomething(a);
   }
};

int main() {
   const test a;
   // You're not in for a good time:
   a.doSomething(12345);
   return 1;
}

当提供需要重复代码的函数的 const 和非 const 版本时,最好实现 const 版本,然后非 const 版本以特定方式调用它。

来自斯科特迈尔斯 Effective C++ - Third Edition :

When const and non-const member functions have essentially identical implementation, code duplication can be avoided by having the non-const version call the const version

Scott Myers 继续提供了一种安全的方法来做到这一点:

const int* doSomething(int a) const
{
   int* someInt = new int;
   *someInt = a;
   return someInt;
}

int* doSomething(int a)
{
   return const_cast<int*>(static_cast<const Test&>(*this).doSomething());
}

在非const 版本中,有两个转换:static_cast 基本上将this 转换为const this,其中 const_cast 抛弃了返回的 const 特性。这样做是安全的,因为要调用非 const 版本,您必须有一个非 const this

但是,如果您只是向成员提供访问权限,那么只需要以下内容就简单易懂:

class TestAccess;
class Test
{
    TestAccess& t;
public:
    const TestAccess& getA() const { return t; }
    TestAcess& getA() { return t; }
};

关于c++ - 这可能会导致无限循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983555/

相关文章:

java - 如何以编程方式将边距中的 px 转换为 dp?

c# - 为什么这是合法的?引用类型中的常量,从属性 *on* 类型,没有类型名称前缀?

c++ - C++ 类中的指针变得杂乱无章

c++ - 跳转二分查找有直观的解释吗?

javascript - 递归异步 api 调用

c - 分段故障核心转储: Function that returns the next prime number

java - 二维递归

c++ - 为什么三元运算符中的多个语句不执行

c++ - 是否有适用于 C++ 的线程安全图形库?

c++ - C++类中的静态常量成员