【发布时间】:2010-09-25 22:38:46
【问题描述】:
我在这里阅读了这个question here 关于 const 正确性的内容。 Scott Meyer 解决方案似乎是一个很好的解决方法,但是如果您有一个使用 this 指针的成员函数(需要 const 和非 const 版本)怎么办。如果成员函数是const,那么this 自动表示const this,这使得在大部分代码所在的位置很难有一个const 函数。
我想到的一种可能的解决方法是将this 的引用作为参数传递给 const 函数,因此该函数可以使用该引用而不是直接使用this 指针。但是,这样安全吗?它似乎是安全的(如果非常hacky),因为您实际上并没有在const-object上使用const_cast。相反,您只是通过传递对象的非常量引用来规避const 成员函数提供的契约。
例如:
class Foo
{
private:
template <class SelfReference>
void f1(SelfReference& self) const
{
// We now might have a non-const reference to "this", even though
// we're in a const member function. But is this safe???
}
public:
void f2()
{
f1(*this);
}
void f2() const
{
f1(*this);
}
};
这似乎提供了一种很好的方法,可以避免在需要函数的 const 和非 const 版本时重复大量代码,但这安全吗?还是它会以某种方式导致未定义的行为?
【问题讨论】:
-
可能是this的副本?
标签: c++ constants code-duplication const-correctness