const_cast:仅当原始变量为 const 时,修改以前的 const 值才未定义

Aqu*_*irl 0 c++ c++11

/sf/answers/23246051/

仅当原始变量为 const 时,修改以前的 const 值才未定义

...

如果您使用它来取消对未使用 const 声明的内容的引用的 const,则它是安全的。

...

例如,这在基于 const 重载成员函数时很有用。它还可以用于向对象添加 const,例如调用成员函数重载。

我无法理解上述引用的含义。我请求你给我一些例子来实际说明这些引文的含义。

dfr*_*fri 6

关于你的前两个报价:

void do_not_do_this(const int& cref) {
    const_cast<int&>(cref) = 42;
}

int main() {
    int a = 0;
    // "if you use it to take the const off a reference 
    // to something that wasn't declared with const, it is safe."
    do_not_do_this(a);  // well-defined
        // a is now 42.
    
    // "modifying a formerly const value is only 
    //  undefined if the original variable is const"
    const int b = 0;
    do_not_do_this(a);  // undefined behavoiur
}
Run Code Online (Sandbox Code Playgroud)

关于您的最终报价:

// "This can be useful when overloading member functions based
//  on const, for instance. It can also be used to add const
//  to an object, such as to call a member function overload."
class A {
    const int& get() const
    {
        // ... some common logic for const and
        // non-const overloads.
        return a_;
    }

    int& get() {
        // Since this get() overload is non-const, the object itself
        // is non-const in this scope. Moreover, the a_ member
        // is non-const, and thus casting away the const of the return
        // from the const get() (after 'this' has been casted to
        // const) is safe.
        A const * const c_this = this;
        return const_cast<int&>(c_this->get());
    }
    
private:
    int a_{0}; 
}
Run Code Online (Sandbox Code Playgroud)