为什么 const 限定符不处理 const 对象上的指针成员?
Why isn't the const qualifier working on pointer members on const objects?
我知道这个问题已经被问了很多,但我能找到的唯一答案是当常量实际上被使用 (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++》一书中读到更多关于它的信息
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- std :: allocator_traits ::用const指针构造
- 汇编问题试图使用qobject_cast进行const指针
- C++ 两个具有相互指向 const 指针的对象
- 我想将指向 const 对象的指针放入包含非 const 指针的容器中.我有什么选择
- 传统代码突变const指针.任何合法的原因
- C#等效于C 中的const指针
- 返回指向 const 数据成员和 'auto' 关键字的 const 指针。有点困惑
- 函数返回由const指针向量生成的指针
- 您如何使用成员正确初始化构造的结构,该构件是指向const值的const指针
- 使用 const 指针的 C 样式字符返回不正确的结果
- 有没有办法将 std::stack<pointer> 转换为 std::stack<const 指针>?
- 为什么当 typedef const 指针与额外的 const 一起使用时,编译器不会给出错误?
- 如何将const_cast的const指针向量映射到非常量指针向量
- 什么场景可能需要使用 需要 const 指针指向(非常量常量)数据
- 强制转换 const 指针以使用旧版 C 代码
- const ref 和 const 指针 c++ 之间的区别
- 将 const 传递给接受 const 指针的函数是不正确的
- 指向指针数组的Const指针
- C++Const指针声明