调用 const 函数而不是其非 const 版本

Calling a const function rather than its non-const version(调用 const 函数而不是其非 const 版本)
本文介绍了调用 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 版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)