Why const_cast is not modifying the value in caller function?

后端 未结 1 842
悲哀的现实
悲哀的现实 2020-12-12 02:08

For below snippet,

#include 
using namespace std;

void fun(const int *p)
{
    int *q = const_cast(p);
    *q = *q * 10;
    co         


        
相关标签:
1条回答
  • 2020-12-12 03:02

    Is it some kind of undefined behavior with const_cast ?

    Yes, your program contains undefined behavior.

    This means that you cannot have any expectation on its output. The reason is given by paragraph 7.1.6.1/4 of the C++11 Standard:

    Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior

    Paragraph 5.2.11/7 on const_cast contains a further warning:

    [ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). —end note ]

    0 讨论(0)
提交回复
热议问题