首页 > 解决方案 > 抛弃 *this 的 const 会导致未定义的行为吗?

问题描述

以下代码编译。它似乎运行良好。

但它会导致任何未定义的行为吗?

我想抛弃*this.

这是为了允许 aconst my_iterator改变它指向的数据。

测试:

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

标签: c++constantsundefined-behavior

解决方案


您的示例不是未定义的行为,因为ais not const。但是,如果aconst,它将是:

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

推荐阅读