簡體   English   中英

是否舍棄* this的const會導致不確定的行為?

[英]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 但是,如果aconst ,則為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM