C++ 中的只读块

问题描述 投票:0回答:2

在 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(); ... } };
我想知道是否有办法解决这个问题。

c++
2个回答
0
投票
在 C++ 中,您不能将块作用域标记为

const

 (或类似的)来指定不应修改 
*this


0
投票
你可以这样做:

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); } };
不确定这是否算作“仅一个区块”。它对于方法来说是本地的。有用。这就是所有的优点。这绝对不值得这么麻烦。

您的解决方法是我能想到的最清晰的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.