[英]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
的const。
This is for allowing a const my_iterator
to mutate the data it points at. 这是为了允许
const my_iterator
对其指向的数据进行突变。
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
. 您的示例不是未定义的行为,因为
a
不是const
。 However, if a
were const
, it would be: 但是,如果
a
为const
,则为:
int main() {
const A a(10);
a.set_x2(100);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.