Undefined behaviour with const_cast

前端 未结 7 2238
孤街浪徒
孤街浪徒 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:08

    What is puzzling me is why this appears to work

    That is what undefined behavior means.
    It can do anything including appear to work.
    If you increase your optimization level to its top value it will probably stop working.

    but doesn't even prompt me with a warning to notify me that this behaviour is undefined.

    At the point it were it does the modification the object is not const. In the general case it can not tell that the object was originally a const, therefore it is not possible to warn you. Even if it was each statement is evaluated on its own without reference to the others (when looking at that kind of warning generation).

    Secondly by using cast you are telling the compiler "I know what I am doing override all your safety features and just do it".

    For example the following works just fine: (or will seem too (in the nasal deamon type of way))

    float aFloat;
    
    int& anIntRef = (int&)aFloat;  // I know what I am doing ignore the fact that this is sensable
    int* anIntPtr = (int*)&aFloat;
    
    anIntRef  = 12;
    *anIntPtr = 13;
    

    I know that const_casts are, broadly speaking, frowned upon

    That is the wrong way to look at them. They are a way of documenting in the code that you are doing something strange that needs to be validated by smart people (as the compiler will obey the cast without question). The reason you need a smart person to validate is that it can lead to undefined behavior, but the good thing you have now explicitly documented this in your code (and people will definitely look closely at what you have done).

    but I can imagine a case where lack of awareness that C-style cast can result in a const_cast being made could occur without being noticed, for example:

    In C++ there is no need to use a C style cast.
    In the worst case the C-Style cast can be replaced by reinterpret_cast<> but when porting code you want to see if you could have used static_cast<>. The point of the C++ casts is to make them stand out so you can see them and at a glance spot the difference between the dangerous casts the benign casts.

提交回复
热议问题