Does cast away const of *this cause undefined behavior?

大兔子大兔子 提交于 2019-12-24 00:56:21

问题


The following code compiles. It seems to run fine.

But would it cause any undefined behavior?

I want to cast away the const of *this.

This is for allowing a const my_iterator to mutate the data it points at.

Test:

class A {
public:
    A(const int x) : x_(x) {}
    void set_x(int x) { x_ = x; }
    void set_x2(const int x) const {
        const_cast<A&>(*this).set_x(x);
    }
    int x_;
};

int main() {
    A a(10);
    a.set_x2(100);
}

回答1:


Your example is not undefined behavior because a is not const. However, if a were const, it would be:

int main() {
    const A a(10);
    a.set_x2(100);
}


来源:https://stackoverflow.com/questions/50163959/does-cast-away-const-of-this-cause-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!