Calling a const function rather than its non-const version(调用 const 函数而不是其非 const 版本)
问题描述
为了我的目的,我尝试包装类似于 Qt 的共享数据指针的东西,经过测试,我发现应该调用 const 函数时,选择了它的非 const 版本.
I tried to wrap something similar to Qt's shared data pointers for my purposes, and upon testing I found out that when the const function should be called, its non-const version was chosen instead.
我正在使用 C++0x 选项进行编译,这是一个最小的代码:
I'm compiling with C++0x options, and here is a minimal code:
struct Data {
int x() const {
return 1;
}
};
template <class T>
struct container
{
container() {
ptr = new T();
}
T & operator*() {
puts("non const data ptr");
return *ptr;
}
T * operator->() {
puts("non const data ptr");
return ptr;
}
const T & operator*() const {
puts("const data ptr");
return *ptr;
}
const T * operator->() const {
puts("const data ptr");
return ptr;
}
T* ptr;
};
typedef container<Data> testType;
void testing() {
testType test;
test->x();
}
如您所见,Data.x 是一个 const 函数,因此调用的运算符 -> 应该是 const 的.当我注释掉非常量时,它编译时没有错误,所以这是可能的.然而我的终端打印:
As you can see, Data.x is a const function, so the operator -> called should be the const one. And when I comment out the non-const one, it compiles without errors, so it's possible. Yet my terminal prints:
"非常量数据指针"
这是一个 GCC 错误(我有 4.5.2),还是我遗漏了什么?
Is it a GCC bug (I have 4.5.2), or is there something I'm missing?
推荐答案
如果你有两个仅在 const
方面不同的重载,那么编译器会根据 *this
是否为 const
.在您的示例代码中,test
不是 const
,因此调用了非 const
重载.
If you have two overloads that differ only in their const
-ness, then the compiler resolves the call based on whether *this
is const
or not. In your example code, test
is not const
, so the non-const
overload is called.
如果你这样做了:
testType test;
const testType &test2 = test;
test2->x();
你应该看到另一个重载被调用了,因为 test2
是 const
.
you should see that the other overload gets called, because test2
is const
.
这篇关于调用 const 函数而不是其非 const 版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调用 const 函数而不是其非 const 版本


基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01