简体   繁体   中英

Does cast away const of *this cause undefined behavior?

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);
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM