Undefined behaviour with const_cast

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

    Undefined behaviour literally means just that: behaviour which is not defined by the language standard. It typically occurs in situations where the code is doing something wrong, but the error can't be detected by the compiler. The only way to catch the error would be to introduce a run-time test - which would hurt performance. So instead, the language specification tells you that you mustn't do certain things and, if you do, then anything could happen.

    In the case of writing to a constant object, using const_cast to subvert the compile-time checks, there are three likely scenarios:

    • it is treated just like a non-constant object, and writing to it modifies it;
    • it is placed in write-protected memory, and writing to it causes a protection fault;
    • it is replaced (during optimisation) by constant values embedded in the compiled code, so after writing to it, it will still have its initial value.

    In your test, you ended up in the first scenario - the object was (almost certainly) created on the stack, which is not write protected. You may find that you get the second scenario if the object is static, and the third if you enable more optimisation.

    In general, the compiler can't diagnose this error - there is no way to tell (except in very simple examples like yours) whether the target of a reference or pointer is constant or not. It's up to you to make sure that you only use const_cast when you can guarantee that it's safe - either when the object isn't constant, or when you're not actually going to modify it anyway.

提交回复
热议问题