在const对象上间接调用非const函数,如何改写为长尾?
- 内容介绍
- 文章标签
- 相关推荐
本文共计345个文字,预计阅读时间需要2分钟。
给定的代码是一个简单的C++类定义和主函数。以下是修改后的内容,不包含数字,不超过100个字:
cppclass foo;foo* instance=NULL;class foo {public: explicit foo(int j) : i(j) { instance=this; } void inc() { ++i; }private: int i;};const foo f(0);int main() { instance->inc();}
给出以下代码:class foo; foo* instance = NULL; class foo { public: explicit foo(int j) : i(j) { instance = this; } void inc() { ++i; } private: int i; };
以下是使用定义的行为吗?
const foo f(0); int main() { instance->inc(); }
我问,因为我正在使用类注册表,因为我不直接修改f将它设为const会很好,但后来f会被注册表间接修改.
编辑:通过定义的行为我的意思是:对象放置在一些特殊的内存位置,只能写入一次?只读存储器是不可能的,至少在C 1x的constexpr之前.例如,常量基本类型(通常)被放入只读内存中,对其执行const_cast可能会导致未定义的行为,例如:
int main() { const int i = 42; const_cast<int&>(i) = 0; // UB } 是的,根据7.1.5.1/4,它是未定义的行为:
Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
请注意,对象的生命周期在构造函数调用完成后开始(3.8 / 1).
本文共计345个文字,预计阅读时间需要2分钟。
给定的代码是一个简单的C++类定义和主函数。以下是修改后的内容,不包含数字,不超过100个字:
cppclass foo;foo* instance=NULL;class foo {public: explicit foo(int j) : i(j) { instance=this; } void inc() { ++i; }private: int i;};const foo f(0);int main() { instance->inc();}
给出以下代码:class foo; foo* instance = NULL; class foo { public: explicit foo(int j) : i(j) { instance = this; } void inc() { ++i; } private: int i; };
以下是使用定义的行为吗?
const foo f(0); int main() { instance->inc(); }
我问,因为我正在使用类注册表,因为我不直接修改f将它设为const会很好,但后来f会被注册表间接修改.
编辑:通过定义的行为我的意思是:对象放置在一些特殊的内存位置,只能写入一次?只读存储器是不可能的,至少在C 1x的constexpr之前.例如,常量基本类型(通常)被放入只读内存中,对其执行const_cast可能会导致未定义的行为,例如:
int main() { const int i = 42; const_cast<int&>(i) = 0; // UB } 是的,根据7.1.5.1/4,它是未定义的行为:
Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
请注意,对象的生命周期在构造函数调用完成后开始(3.8 / 1).

