抛弃 *这会导致未定义的行为吗?

Does cast away const of *this cause undefined behavior?

本文关键字:未定义 抛弃      更新时间:2023-10-16

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

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

我想抛弃*this的常量.

这是为了允许const 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);
}

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

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