在 C++ 中,可以使用
const
关键字声明成员函数,这样它就不能修改对象(除了可能是可变字段)。
问题:有没有办法只写一个块,使其无法修改对象?
举个例子,我想它可能看起来像这样:
class A {
void f() { // non-const member
... // this code might modify *this
const {
... // this code cannot modify *this
}
...
}
};
我们可以通过这样的函数调用来实现这一点:
class A {
void _f() const {
... // this code cannot modify *this
}
void f() { // non-const member
... // this code might modify *this
_f();
...
}
};
我想知道是否有办法解决这个问题。
const
(或类似的)来指定不应修改
*this
。
class A {
void f() {
{
const auto self = *this;
// self is const
}
}
};
但是,this
仍在范围内。您还可以声明一个带有
const
引用的自定义函子:
struct foo {
void bar() {
struct foobar {
void operator()(const foo& f) {
// f is const here
}
};
foobar{}(*this);
}
};
不确定这是否算作“仅一个区块”。它对于方法来说是本地的。有用。这就是所有的优点。这绝对不值得这么麻烦。您的解决方法是我能想到的最清晰的解决方案。