通过从构造函数中的 'this' 复制的指针改变常量对象

Mutating constant object via pointer copied from 'this' in constructor

示例代码:

struct Foo {
    Foo() { instance = this; }
    int value = 0;
    static Foo * instance;
};

Foo * Foo::instance = nullptr;

int main(int argc, char * argv[]) {
    Foo const foo;
    //foo.value = 1; // Compiler error, as expected.
    Foo::instance->value = 1; // Fine.
}

这里的foo是常量,但是可以通过静态instance指针修改,在Foo的构造函数中它被赋值为this。抛开为什么有人可能想要做这样的事情的问题,我的理解是这里没有任何技术上的错误。

我确信这是安全的,但在 this 线程中似乎有一些相反的建议。一个人似乎将类似的示例描述为格式错误,而其他人则提到未定义的行为。

撇开建议不谈,这在技术上是否正确且安全?还是我遗漏了一些问题?

这样做绝对是不明智的。有很多原因。

首先,它不是线程安全的。

其次,通过 "unconsting" 通过 const_cast 或通过您展示的方法(或通过任何其他方法)对 const 限定对象进行变异,只是 未定义的行为.