[英]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.