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

查看:30
本文介绍了调用 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();

你应该看到另一个重载被调用了,因为 test2const.

you should see that the other overload gets called, because test2 is const.

这篇关于调用 const 函数而不是其非 const 版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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