给出以下代码: 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();} 我问
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).
