无需 const_cast 即可修改 *this 的 Const 方法
我正在编写的程序中出现了以下模式。我希望它不是太做作,但它设法在 const 方法 Foo::Questionable() const
中改变 <code>Foo 对象,而不使用任何 const_cast 或类似的方法。基本上,Foo
存储对 FooOwner
的引用,反之亦然,并且在 Questionable()
中,Foo
设法修改通过对其所有者调用 mutate_foo()
来将其自身放入 const 方法中。问题遵循代码。
#include "stdafx.h"
#include <iostream>
using namespace std;
class FooOwner;
class Foo {
FooOwner& owner;
int data;
public:
Foo(FooOwner& owner_, int data_)
: owner(owner_),
data(data_)
{
}
void SetData(int data_)
{
data = data_;
}
int Questionable() const; // defined after FooOwner
};
class FooOwner {
Foo* pFoo;
public:
FooOwner()
: pFoo(NULL)
{}
void own(Foo& foo)
{
pFoo = &foo;
}
void mutate_foo()
{
if (pFoo != NULL)
pFoo->SetData(0);
}
};
int Foo::Questionable() const
{
owner.mutate_foo(); // point of interest
return data;
}
int main()
{
FooOwner foo_owner;
Foo foo(foo_owner, 0); // foo keeps reference to foo_owner
foo_owner.own(foo); // foo_owner keeps pointer to foo
cout << foo.Questionable() << endl; // correct?
return 0;
}
这是定义的行为吗? Foo::data
应该被声明为可变的吗?或者这是我做错事的迹象?我正在尝试实现一种延迟初始化的“数据”,它仅在请求时设置,并且以下代码编译良好,没有警告,所以我有点紧张,因为我在 UB 土地上。
编辑:Questionable() 上的 const
仅使直接成员为 const,而不是对象指向或引用的对象。这使代码合法吗?我对以下事实感到困惑:在 Questionable()
中,this
的类型为 const Foo*
,而在调用堆栈的更深处,< code>FooOwner 合法地拥有一个用于修改 Foo
的非常量指针。这是否意味着 Foo
对象可以修改?
编辑2:也许是一个更简单的例子:
class X {
X* nonconst_this; // Only turns in to X* const in a const method!
int data;
public:
X()
: nonconst_this(this),
data(0)
{
}
int GetData() const
{
nonconst_this->data = 5; // legal??
return data;
}
};
The following pattern has arisen in a program I'm writing. I hope it's not too contrived, but it manages to mutate a Foo
object in the const method Foo::Questionable() const
, without use of any const_cast or similar. Basically, Foo
stores a reference to FooOwner
and vice versa, and in Questionable()
, Foo
manages to modify itself in a const method by calling mutate_foo()
on its owner. Questions follow the code.
#include "stdafx.h"
#include <iostream>
using namespace std;
class FooOwner;
class Foo {
FooOwner& owner;
int data;
public:
Foo(FooOwner& owner_, int data_)
: owner(owner_),
data(data_)
{
}
void SetData(int data_)
{
data = data_;
}
int Questionable() const; // defined after FooOwner
};
class FooOwner {
Foo* pFoo;
public:
FooOwner()
: pFoo(NULL)
{}
void own(Foo& foo)
{
pFoo = &foo;
}
void mutate_foo()
{
if (pFoo != NULL)
pFoo->SetData(0);
}
};
int Foo::Questionable() const
{
owner.mutate_foo(); // point of interest
return data;
}
int main()
{
FooOwner foo_owner;
Foo foo(foo_owner, 0); // foo keeps reference to foo_owner
foo_owner.own(foo); // foo_owner keeps pointer to foo
cout << foo.Questionable() << endl; // correct?
return 0;
}
Is this defined behavior? Should Foo::data
be declared mutable? Or is this a sign I'm doing things fatally wrong? I'm trying to implement a kind of lazy-initialised 'data' which is only set when requested, and the following code compiles fine with no warnings, so I'm a little nervous I'm in UB land.
Edit: the const
on Questionable() only makes immediate members const, and not the objects pointed to or referenced by the object. Does this make the code legal? I'm confused between the fact that in Questionable()
, this
has the type const Foo*
, and further down the call stack, FooOwner
legitimately has a non-const pointer it uses to modify Foo
. Does this mean the Foo
object can be modified or not?
Edit 2: perhaps an even simpler example:
class X {
X* nonconst_this; // Only turns in to X* const in a const method!
int data;
public:
X()
: nonconst_this(this),
data(0)
{
}
int GetData() const
{
nonconst_this->data = 5; // legal??
return data;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
考虑以下情况:
i
是一个对象,并且其类型为int
。它不是 cv 限定的(不是const
或volatile
,或两者。)现在我们添加:
j
是一个引用 < code>i,k
是指向i
的指针。 (从现在开始,我们只需将“refer to”和“points to”合并为“points to”。)此时,我们有两个 cv 限定变量,
j
和k
,指向非 cv 限定的对象。 §7.1 中提到了这一点。 5.1/3:这意味着编译器必须尊重
j
和k
是 cv 限定的,即使它们指向非 cv 限定的对象。 (因此,j = 5
和*k = 5
是非法的,尽管i = 5
是合法的。)我们现在考虑删除
>const
from those:这是合法的(§参考5.2.11),但它是未定义的行为吗? 否。请参阅第 7.1 节。 5.1/4:
记住
i
不是const
并且j
和k
都指向i
。我们所做的就是告诉类型系统从类型中删除 const 限定符,以便我们可以修改指向的对象,然后通过这些变量修改i
。这与这样做完全相同:
And this is trivially legal.我们现在认为
i
是这样的:现在我们的代码是什么?
现在它会导致未定义的行为,因为
i
是一个const限定的对象。我们告诉类型系统删除 const,以便我们可以修改指向的对象,然后修改 const 限定对象。正如上面引用的,这是未定义的。再次,更明显的是:
请注意,简单地这样做:
是完全合法和定义的,因为没有 const 限定的对象被修改;我们只是在搞乱类型系统。
现在考虑一下:
bar
上的const
对成员做了什么?它使对它们的访问通过称为cv 限定的访问路径的方式进行。 (它通过将this
的类型从T* const
更改为cv T const*
来实现此目的,其中cv
是函数上的 cv 限定符。)那么
bar
执行期间的成员类型是什么?它们是:当然,类型是无关紧要的,因为重要的是指向对象的const限定,而不是指针。 (如果上面的
k
是const int* const
,则后面的const
是无关紧要的。)我们现在考虑:在
bar
内>,me
和self
都指向一个非常量foo
,所以就像上面的int i
一样有明确的行为。如果我们有:我们就会有 UB,就像 const int 一样,因为我们将修改 const 限定的对象。
在你的问题中,你没有 const 限定的对象,所以你没有未定义的行为。
为了增加对权威的吸引力,请考虑 Scott Meyers 的 const_cast 技巧,用于在非常量函数中回收 const 限定函数:
他建议:
或者通常如何编写:
请注意这一点再次强调,这是完全合法且明确定义的。具体来说,因为必须在非 const 限定的
foo
上调用此函数,所以我们可以完全安全地从int& 的返回类型中剥离 const 限定。 boo() 常量
。(除非有人一开始就用
const_cast
+ 调用自杀。)总结一下:
我参考了 ISO C++03 标准。
Consider the following:
i
is an object, and it has the typeint
. It is not cv-qualified (is notconst
orvolatile
, or both.)Now we add:
j
is a reference which refers toi
, andk
is a pointer which points toi
. (From now on, we simply combine "refer to" and "points to" to just "points to".)At this point, we have two cv-qualified variables,
j
andk
, that point to a non-cv-qualified object. This is mentioned in §7.1.5.1/3:What this means is that a compiler must respect that
j
andk
are cv-qualified, even though they point to a non-cv-qualified object. (Soj = 5
and*k = 5
are illegal, even thoughi = 5
is legal.)We now consider removing the
const
from those:This is legal (§refer to 5.2.11), but is it undefined behavior? No. See §7.1.5.1/4:
Remember that
i
is notconst
and thatj
andk
both point toi
. All we've done is tell the type system to remove the const-qualifier from the type so we can modify the pointed to object, and then modifiedi
through those variables.This is exactly the same as doing:
And this is trivially legal. We now consider that
i
was this instead:What of our code now?
It now leads to undefined behavior, because
i
is a const-qualified object. We told the type system to removeconst
so we can modify the pointed to object, and then modified a const-qualified object. This is undefined, as quoted above.Again, more apparent as:
Note that simply doing this:
Is perfectly legal and defined, as no const-qualified objects are being modified; we're just messing with the type-system.
Now consider:
What does
const
onbar
do to the members? It makes access to them go through something called a cv-qualified access path. (It does this by changing the type ofthis
fromT* const
tocv T const*
, wherecv
is the cv-qualifiers on the function.)So what are the members types during the execution of
bar
? They are:Of course, the types are irrelevant, as the important thing is the const-qualification of the pointed to objects, not the pointers. (Had
k
above beenconst int* const
, the latterconst
is irrelevant.) We now consider:Within
bar
, bothme
andself
point to a non-constfoo
, so just like withint i
above we have well-defined behavior. Had we had:We would have had UB, just like with
const int
, because we would be modifying a const-qualified object.In your question, you have no const-qualified objects, so you have no undefined behavior.
And just to add an appeal to authority, consider the
const_cast
trick by Scott Meyers, used to recycle a const-qualified function in a non-const function:He suggests:
Or how it's usually written:
Note this is, again, perfectly legal and well-defined. Specifically, because this function must be called on a non-const-qualified
foo
, we are perfectly safe in stripping the const-qualification from the return type ofint& boo() const
.(Unless someone shoots themselves with a
const_cast
+ call in the first place.)To summarize:
I refer to the ISO C++03 standard.
IMO,你没有做任何技术上错误的事情。如果该成员是一个指针,也许会更容易理解。
const
使指针成为const,而不是被指向者。考虑以下之间的区别:
对于引用,由于它们无论如何都无法重新定位,因此方法上的
const
关键字对引用成员没有任何影响。在你的例子中,我没有看到任何 const 对象,所以你没有做任何坏事,只是利用了 C++ 中 const 正确性工作方式中的一个奇怪的漏洞。
IMO, you are not doing anything technically wrong. May-be it would be simpler to understand if the member was a pointer.
const
makes the pointer const, not the pointee.Consider the difference between:
As to references, since they can't be reseated anyway, the
const
keyword on the method has no effect whatsoever on reference members.In your example, I don't see any const objects, so you are not doing anything bad, just exploiting a strange loophole in the way const correctness works in C++.
在没有真正了解它是否/应该/可以被允许的情况下,我强烈建议反对它。语言中有一些机制可以实现您想要实现的目标,不需要编写很可能会让其他开发人员感到困惑的晦涩构造。
查看
mutable
关键字。该关键字可用于声明可在 const 成员方法中修改的成员,因为它们不会影响类的可感知状态。考虑使用一组参数初始化并执行可能并不总是需要的复杂昂贵计算的类:一种可能的实现是将结果值添加为成员并为每个组计算它:
但这意味着该值是在所有套装,无论是否需要。如果您将对象视为黑匣子,则该接口仅定义一个用于设置参数的方法和一个用于检索计算值的方法。执行计算的瞬间并不真正影响对象的感知状态——只要 getter 返回的值是正确的。因此,我们可以修改该类来存储输入(而不是输出),并仅在需要时计算结果:
从语义上讲,第二类和第一类是等效的,但现在我们避免了在值不是时执行复杂的计算。需要,因此如果仅在某些情况下请求该值是一个优势。但同时,如果对同一对象多次请求该值也是一个缺点:即使输入没有更改,每次也会执行复杂的计算。
解决方案是缓存结果。为此我们可以将结果传达给班级。当请求结果时,如果我们已经计算了它,我们只需要检索它,而如果我们没有该值,我们必须计算它。当输入发生变化时,我们会使缓存失效。这就是
mutable
关键字派上用场的时候。它告诉编译器该成员不是可感知状态的一部分,因此可以在常量方法中对其进行修改:第三个实现在语义上等同于前两个版本,但如果结果已经是则避免重新计算值已知并缓存。
在其他地方需要
mutable
关键字,例如在多线程应用程序中,类中的互斥体通常被标记为mutable
。锁定和解锁互斥体是互斥体的变异操作:其状态明显发生变化。现在,在不同线程之间共享的对象中的 getter 方法不会修改感知的状态,但如果操作必须是线程安全的,则必须获取和释放锁:getter 操作在语义上是恒定的,即使它需要修改互斥体以确保单线程访问
value
成员。Without actually getting to whether it is/should/could be allowed, I would greatly advice against it. There are mechanisms in the language for what you want to achieve that don't require writing obscure constructs that will most probably confuse other developers.
Look into the
mutable
keyword. That keyword can be used to declare members that can be modified withinconst
member methods as they do not affect the perceivable state of the class. Consider class that gets initialized with a set of parameters and performs a complex expensive calculation that may not be needed always:A possible implementation is adding the result value as a member and calculating it for each set:
But this means that the value is calculated in all sets, whether it is needed or not. If you think on the object as a black box, the interface just defines a method to set the parameters and a method to retrieve the calculated value. The instant when the calculation is performed does not really affect the perceived state of the object --as far as the value returned by the getter is correct. So we can modify the class to store the inputs (instead of the outputs) and calculate the result only when needed:
Semantically the second class and the first class are equivalent, but now we have avoided to perform the complex calculation if the value is not needed, so it is an advantage if the value is only requested in some cases. But at the same time it is a disadvantage if the value is requested many times for the same object: each time the complex calculation will be performed even if the inputs have not changed.
The solution is caching the result. For that we can the result to the class. When the result is requested, if we have already calculated it, we only need to retrieve it, while if we do not have the value we must calculate it. When the inputs change we invalidate the cache. This is when the
mutable
keyword comes in handy. It tells the compiler that the member is not part of the perceivable state and as such it can be modified within a constant method:The third implementation is semantically equivalent to the two previous versions, but avoid having to recalculate the value if the result is already known --and cached.
The
mutable
keyword is needed in other places, like in multithreaded applications the mutex in classes are often marked asmutable
. Locking and unlocking a mutex are mutating operations for the mutex: its state is clearly changing. Now, a getter method in an object that is shared among different threads does not modify the perceived state but must acquire and release the lock if the operation has to be thread safe:The getter operation is semantically constant, even if it needs to modify the mutex to ensure single threaded access to the
value
member.const
关键字仅在编译时检查期间被考虑。 C++ 没有提供任何工具来保护您的类免受任何内存访问,而这正是您对指针/引用所做的事情。编译器和运行时都无法知道您的指针是否指向您在某处声明为 const 的实例。编辑:
简短的示例(可能无法编译):
在这种情况下,编译器可能会决定,ey,foo.datalength 是 const,
并且循环内的代码承诺不会更改 foo,所以我必须评估
当我进入循环时,数据长度仅一次。雅皮士!
如果你尝试调试这个错误,这个错误很可能只有在你使用优化编译(而不是在调试版本中)时才会出现,你会让自己发疯的。
信守承诺!或者使用 mutable 让你的脑细胞保持高度警惕!
The
const
keyword is only considered during compile time checks. C++ provides no facilities to protect your class against any memory access, which is what you are doing with your pointer/reference. Neither the compiler nor the runtime can know if your pointer points to an instance that you declared const somewhere.EDIT:
Short example (might not compile):
In this case, the compiler might decide, ey, foo.datalength is const,
and the code inside the loop promised not to change foo, so I have to evaluate
datalength only once when I enter the loop. Yippie!
And if you try to debug this error, which will most likely only turn up if you compile with optimizations (not in the debug builds) you will drive yourself crazy.
Keep the promises! Or use mutable with your braincells on high alert!
您已经达到了循环依赖关系。请参阅常见问题解答 39.11 是的,即使您已经绕过了编译器,修改
const
数据也是 UB 的。此外,如果您不遵守承诺(请阅读:违反const
),您将严重损害编译器的优化能力。如果您知道将通过调用其所有者来修改它,为什么
有问题
const
?为什么被拥有的对象需要知道所有者?如果您确实需要这样做,那么mutable
就是正确的选择。这就是它的作用——逻辑常量(与严格的位级常量相对)。从我的 n3090 草案副本中:
[注意强调我的]。
关于布法罗:
You have reached circular dependencies. See FAQ 39.11 And yes, modifying
const
data is UB even if you have circumvented the compiler. Also, you are severely impairing the compiler's capacity to optimize if you don't keep your promises (read: violateconst
).Why is
Questionable
const
if you know that you will modify it via a call to its owner? Why does the owned object need to know about the owner? If you really really need to do that thenmutable
is the way to go. That is what it is there for -- logical constness (as opposed to strict bit level constness).From my copy of the draft n3090:
[Note emphasis mine].
On UB: