为了定义函数的第二个 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 theconst
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/