指针和引用作为const对象的成员变量 [英] Pointers and References as member variables of const objects
问题描述
以下代码可以正常编译。但是我不知道这是否合法的C ++。因此,更具体地说,如果我有一个const对象,是否可以通过该对象的指针/引用来修改变量?
The following code compiles fine. However I wonder if it is legal C++. So more specific, if I have a const object, am I allowed to modify variables through pointers/references of that object?
class Foo {
public:
int* a;
int& b;
Foo(int* _a, int& _b) : a(_a), b(_b) {}
};
int main ( int argc, char* argv[] ) {
int x = 7;
const Foo bar(&x, x);
*bar.a = 3; //Leagal?
bar.b = 7; //Legal?
return 0;
}
推荐答案
这是合法的,因为const-类的级别表示类成员是恒定的。 a
是一个指针,因此指针指向的地址是恒定的,但存储在该地址的值不必是恒定的。
It's legal, as const-ness of the class means that the class member is constant. a
is a pointer, so the address the pointer points to is constant, but the value stored at that address need not be.
因此, bar.a
实际上是 int * const
,而不是 int const *
。
Hence bar.a
is effectively an int * const
, not an int const *
.
由于初始化后,无论如何都不能引用另一个实体,对于 bar.b
是否将 bar
声明为 const
。
As, after initialization, a reference cannot be made to refer to another entity anyway, it does not matter for bar.b
whether bar
is declared const
or not.
指针的常量变量是常量指针,而不是指向常量的指针。引用的常量变体是引用,而不是对常量的引用。
The constant variant of a pointer is a constant pointer, not a pointer to a constant. The constant variant of a reference is a reference, not a reference to a constant.
小题外话:无论如何,在与const-ness有关的成员中,您都应谨慎对待引用,因为以下内容可能会编译
Small digression: You should be careful with references as members anyway in connection with const-ness, as the following will probably compile
struct Y { int m_a; };
struct X {
const Y & m_y;
X (const Y & y) : m_y (y) { }
};
Y y;
y.m_a = 1;
X x (y); // or const X x (y) -- does not matter
// X.m_y.m_a == 1
y.m_a = 2;
// now X.m_y.m_a == 2, although X.m_y is supposed to be const
由于可以将指向非const的指针分配给指向const的指针,因此可以使用指针构建类似的示例。请记住, const
仅保证您不会通过此非常大的变量来修改变量,它不能保证完全不修改变量的内容。
As it is possible to assign a pointer to non-const to a pointer to const, you can build an analogous example with pointers. Remember that const
does only guarantee that YOU will not modify a variable via this very variable, it cannot guarantee that the contents of the variable are not modified at all.
这篇关于指针和引用作为const对象的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!