Undefined behaviour with const_cast

前端 未结 7 2219
孤街浪徒
孤街浪徒 2020-12-19 01:37

I was hoping that someone could clarify exactly what is meant by undefined behaviour in C++. Given the following class definition:

class Foo
{
public:
             


        
7条回答
  •  抹茶落季
    2020-12-19 02:06

    Undefined behaviour depends on the way the object was born, you can see Stephan explaining it at around 00:10:00 but essentially, follow the code below:

    void f(int const &arg)
    {
        int &danger( const_cast(arg); 
        danger = 23; // When is this UB?
    }
    

    Now there are two cases for calling f

    int K(1);
    f(k); // OK
    const int AK(1); 
    f(AK); // triggers undefined behaviour
    

    To sum up, K was born a non const, so the cast is ok when calling f, whereas AK was born a const so ... UB it is.

提交回复
热议问题