调用const函数而不是其非const版本 [英] Calling a const function rather than its non-const version

查看:229
本文介绍了调用const函数而不是其非const版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了我的目的,我尝试包装类似于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆