下面的代码编译。它似乎运行良好。
但是它会导致任何未定义的行为吗?
我想抛弃 *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
。但是,如果 a
是 const
,它将是:
int main() {
const A a(10);
a.set_x2(100);
}
关于c++ - 丢弃 const of *this 会导致未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50163959/