调用const函数而不是其非const版本 [英] Calling a const function rather than its non-const version
问题描述
为了我的目的,我尝试包装类似于Qt的共享数据指针的东西,并且测试时我发现当const函数应该被调用时,它的非const版本被选择。
我使用C ++ 0x选项进行编译,这里是一个最小代码:
struct数据{
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。当我注释掉非常量,它编译没有错误,所以这是可能的。但我的终端打印:
非const数据ptr
b $ b
是一个GCC错误(我有4.5.2),还是有一些我错过了?
如果你有两个重载,只有 const
ness,那么编译器将根据 * this
是 const
来解析调用。在你的示例代码中, test
不是 const
,所以非 - const $
<$ c $ c> testType test;
const testType& test2 = test;
test2> x();
你应该看到其他重载被调用,因为 test2
是 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.
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();
}
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:
"non const data ptr"
Is it a GCC bug (I have 4.5.2), or is there something I'm missing?
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.
If you did this:
testType test;
const testType &test2 = test;
test2->x();
you should see that the other overload gets called, because test2
is const
.
这篇关于调用const函数而不是其非const版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!