为什么 const 限定符不处理 const 对象上的指针成员?

Why isn't the const qualifier working on pointer members on const objects?

本文关键字:const 指针 成员 对象 处理 为什么      更新时间:2023-10-16

我知道这个问题已经被问了很多,但我能找到的唯一答案是当常量实际上被使用 (int*) 或类似的东西抛弃时。当不涉及强制转换时,为什么 const 限定符不处理 const 对象上的指针类型成员变量?

#include <iostream>
class bar {
public:
    void doit()       { std::cout << "    bar::doit() non-constn"; }
    void doit() const { std::cout << "    bar::doit() constn"; }
};
class foo {
    bar* mybar1;
    bar mybar2;
public:
    foo() : mybar1(new bar) {}
    void doit() const {
        std::cout << "foo::doit() constn";
        std::cout << "  calling mybar1->doit()n";
        mybar1->doit();  // This calls bar::doit() instead of bar::doit() const
        std::cout << "  calling mybar2.doit()n";
        mybar2.doit(); // This calls bar::doit() const correctly
    }
    // ... (proper copying elided for brevity)
};
int main(void)
{
    const foo foobar;  // NOTE: foobar is const
    foobar.doit();
}

上面的代码产生以下输出(在 gcc 4.5.2 和 vc100 中测试):

foo::d oit() const  调用 mybar1->doit()    bar::d oit() non-const <-- Why ?  调用 mybar2.doit()    bar::d oit() const

当 foo 实例是 const 时,它的数据成员也是 const,但这适用于指针的方式与您最初想象的有所不同:

struct A {
  int *p;
};
A const obj;

obj.p 的类型是 int * const,而不是 int const *;也就是说,指向 int 的常量指针,而不是指向常量 int 的指针。

对于另一种看待它的方式,让我们从一个函数开始:

template<class T>
T const& const_(T const &x) {
  return x;
}

现在想象一下我们有一个 A 实例,我们让它变得 const。 您可以将其想象为对每个数据成员应用const_。

A nc;
// nc.p has type int*.
typedef int *T;  // T is the type of nc.p.
T const &p_when_nc_is_const = const_(nc.p);
// "T const" is "int * const".
const T &be_wary_of_where_you_place_const = const_(nc.p);
// "const T" is "int * const".
// "const T" is *not* "const int *".

变量be_wary_of_where_you_place_const显示"添加 const"与在类型的文字文本前面加上"const"不同。

在这种情况下,

我将回答我自己的问题。弗雷德·努尔克的回答是正确的,但并没有真正解释"为什么"。 mybar1*mybar1是不同的。前者指实际指针,后者指对象。指针是常量(由 foo 上的常量规定;你不能做mybar1 = 0),但不是指向的对象,因为这需要我将其声明const bar* mybar1。声明bar* mybar1等效于 foo 对象为 const 时的 bar* const mybar1(即指针是 const,而不是指向对象)。

C++默认给出所谓的按位恒常性 - 这意味着它确保没有一个对象的位被更改,所以它只检查指针的地址。

你可以在S. Meyers的《Effective c++》一书中读到更多关于它的信息