C++、类、Const 和奇怪的语法
我今天重读了 c++ 入门书(第 4 版) - 关于成员函数和 const 引用等的部分,我想出了这个奇怪的小程序:
using std::cout;
using std::endl;
class ConstCheater
{
public:
ConstCheater(int avalue) : ccp(this), value(avalue) {}
ConstCheater& getccp() const {return *ccp;}
int value;
private:
ConstCheater* ccp;
};
int main()
{
const ConstCheater cc(7); //Initialize the value to 7
cout << cc.value << endl;
cc.getccp().value = 4; //Now setting it to 4, even though it's const!
cout << cc.value << endl;
cc.value = 4; //This is illegal
return 0;
}
我的问题是 - 为什么 c++ 允许这样的语法?当类声明为 const 时,为什么我可以编辑类中的普通数据成员? const 的目的不就是让你不能修改值吗?
I was re-reading c++ primer(4th ed.) today - the section on member functions and const references etc, and I came up with this wierd little program:
using std::cout;
using std::endl;
class ConstCheater
{
public:
ConstCheater(int avalue) : ccp(this), value(avalue) {}
ConstCheater& getccp() const {return *ccp;}
int value;
private:
ConstCheater* ccp;
};
int main()
{
const ConstCheater cc(7); //Initialize the value to 7
cout << cc.value << endl;
cc.getccp().value = 4; //Now setting it to 4, even though it's const!
cout << cc.value << endl;
cc.value = 4; //This is illegal
return 0;
}
My question is - why does c++ allow syntax such as this? Why can I edit normal data members in a class when it's declared const? Isn't the POINT of const to make it so that you can't modify values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我想说,您标记为正确的托尼的答案是不正确的,而迈克尔·伯尔的答案是正确的。
更清楚地表达他的意思(至少对我而言):
有两个潜在的误解地方:
this
的方式1. 隐式 const
隐式 const(
ConstCheater
生成const
时内部的 constification)不会将cc
转换为指向 const 的指针
而是一个const-pointer
,也就是说,当您执行此操作时:内部从:
...到...
...而不是
可能具有的 ...已被预料到。
2. const 对象的构造
奇怪的是,自
this
以来,允许在构造函数中将this
传递给cpp
的初始值设定项有人会认为,code>this 应该被视为一个const 指针
,因此不是传递给const 指针
的有效值。也就是说,人们可能期望:
失败,因为从概念上讲,您可能认为这(在某种程度上)相当于:
因此您会认为:
会失败!但事实并非如此,因为显然在构造过程中
this
被特殊对待,就好像它是:因此该对象在构造过程中实际上不是 const。
我不确定我完全理解其中的推理,但迈克尔·伯尔指出,提供预期行为似乎存在逻辑和技术障碍,因此该标准似乎排除了当前有些奇怪的行为。
我最近问了一个相关的问题: 为什么 C++ 没有 const构造函数? 但到目前为止还没有真正完全理解为什么它站不住脚,尽管我认为这会给 C++ 开发人员带来负担,因为他们必须为他们想要的任何类定义一个尴尬的 const 构造函数创建 const 对象。
I'd say the answer by Tony that you marked as correct is incorrect, and the answer by Michael Burr is correct.
To put what he said more clearly (for me at least):
There are two potential places for misunderstanding:
this
is interpreted during construction of a const object1. Implicit Const
Implicit const (the constification internal to
ConstCheater
when it is madeconst
) doesn't turncc
into apointer-to-const
but rather aconst-pointer
, that is to say when you do this:Internally goes from:
...to...
...rather than the...
that may have been expected.
2. Construction of
const
objectThe stranger thing is though is that
this
is allowed to be passed tocpp
's initializer in the constructor sincethis
, one would think, should be treated as apointer-to-const
, and thus not a valid value to pass to aconst-pointer
.That is to say one might expect:
to fail because conceptually you might expect that this was (somewhat) equivalent to:
and thus you would think that:
would fail! But it doesn't because apparently during construction apparently
this
is treated specially as if it was:and thus the object is effectively not const during construction.
I'm not sure I understand completely the reasoning, but Michael Burr points out there appears to be a logical and technical barrier to providing the expected behavior so the standard seems to carve out the current somewhat odd behavior.
I recently asked a related question which was: Why does C++ not have a const constructor? but thus far haven't really understood completely the reasoning why it would be untenable, though I suppose it would place a burden on C++ developers to have to define an awkward const constructor for any class they'd like to create const object of.
构造函数可以修改 const 对象的值,是的。但如果不是的话,它能做什么呢?
由于构造函数具有此类访问权限,因此它可以将其“转发”给其他人或“保存”以供以后使用。当然,这样做可能是一个坏主意。
这是 C++ 的安全机制不会阻止您构建格式错误的程序的一个例子。 C++ 绝不是万无一失的。所以,要小心!
The constructor is allowed to modify the value of a
const
object, yes. But if it weren't, what could it do?Since the constructor has such access, it can "forward" it to someone else or "save" it for later. Of course, doing so might be a bad idea.
This is one instance where the safety mechanisms of C++ do not prevent you from building an ill-formed program. C++ is anything but foolproof. So, just be careful!
对象在其构造函数完成其工作之前不会变为 const。因此,当您存储它时,
this
是一个指向非常量内存的指针,但不久之后就会发生变化。这就是为什么它首先允许分配,因为你没有做错任何事。这意味着 cpp 是一个指向 const 的指针,但编译器没有意识到这一点。它没有办法;毕竟,你声明它是非常量。这仍然是未定义的行为,它只是编译器无法真正希望帮助您捕获的类型。Objects do not become const until after their constructors finish doing their thing. So
this
is a pointer to non-const memory when you store it, but changes shortly after. That's why it allowed the assignment in the first place, because you did nothing wrong. That meanscpp
is a pointer to const, but the compiler doesn't realize that. It has no way to; you declared it non-const, after all. This is still undefined behavior, it's just not the type your compiler can ever really hope to help you catch.真正的问题不是
ConstCheater::getccp()
的行为 - 而是线路上没有错误:它用应该初始化一个非常量指针一个 const
this
指针。然而,构造函数不能是 const(9.3.2/5,但稍微思考一下就可以明白为什么)。因此,构造函数可以使用指向 const 对象(或“即将成为”const 的对象)的指针来初始化非常量指针。那就是你正在开的洞。至于为什么允许它,我想标准很难尝试弥补这个漏洞,因为它必须枚举构造函数的
this
必须被处理const 的所有方式
以及构造 const 对象时必须处理非 const
的所有方式。这似乎是一项相当艰巨的任务。The real issue isn't the behavior of
ConstCheater::getccp()
- it's that there's no error on the line:which initializes a non-const pointer with what should be a const
this
pointer. However, constructors cannot beconst
(9.3.2/5, but a bit of thought should make it obvious why). So the constructor is allowed to initialize a non-const pointer with a pointer to a const object (or an object that's 'about to become' const). That's the hole you're driving though.As to why it's allowed, I imagine it would be difficult for the standard to try to close the hole since it would have to enumerate all the ways that a constructor's
this
would have to be treatedconst
and all the ways it would have to be treatednon-const
when constructing a const object. That seems like a pretty difficult task.您的对象并非完全不可变:只是您创建的指向它的引用是不变的。
Your object is not entirely immutable: it's just the reference you created to point to it that's constant.
您所做的
const
是对ConstCheater
的引用。ConstCheater
中没有任何内容使value
成为const
。What you are making
const
is the reference to aConstCheater
. Nothing inConstCheater
is makingvalue
aconst
.const
限定符限制在对象上调用非常量方法,因此问题在于您的设计允许您通过 const 方法向成员提供非常量引用。常见的方法是
在某些情况下,当对象的逻辑常量不受其成员的外部修改影响时,您可以允许
逻辑常量和形式常量差异的另一个例子是可变成员。即可变可以是在最后一个 const 方法调用时计算的某个术语,如果您在下次调用时获得相同的输入,则可以轻松返回存储的值。
const
qualifier restricts to call non-const methods on your object, so the problem is your design that allows you to give non-const reference to a member by a const method.The common approach is
In some cases when logical constness of your object don't suffer from external modification of it's member you can allow
Another example of difference in logical and formal constness is the
mutable
members. I.e. mutable can be some term that was computed at the lastconst
method's invoke, if you will get the same input at next invoke you can easily return stored value.尽管
getccp()
是一个const
方法,但它不承诺您如何处理它返回的引用。该方法本身不会修改对象,因此不会违反规则。如果它返回一个
const ConstCheater&
那么情况就会不同。正如您的示例所示,
const
比仅将其应用于对象要复杂得多。 C++ FAQ 有一个关于 const 正确性 的部分,特别是 < a href="http://www.parashift.com/c++-faq-lite/const- Correctness.html#faq-18.11" rel="nofollow">它涵盖了您在此处突出显示的情况。Even though
getccp()
is aconst
method it makes no promises what you do with the reference it returns. The method itself does not modify the object and therefore does not break the rules.If it returned a
const ConstCheater&
then that would be different.As your example shows, there is much more complexity to
const
than just applying it to an object. the C++ FAQ has a section on const correctness and in particular it covers the case you are highlighting here.