[英]Does cast away const of *this cause undefined behavior?
以下代码进行编译。 似乎运行良好。
但这会导致任何未定义的行为吗?
我想抛弃*this
的const。
这是为了允许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
。 但是,如果a
为const
,则为:
int main() {
const A a(10);
a.set_x2(100);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.