Is it UB to Modify where pointer points, when original data is const?

后端 未结 2 967
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 00:41

Would it be undefined behavior to change where a pointer points, when its data is const? Example:

const char* p = \"foo\";
p = \"boo\";

I belie

相关标签:
2条回答
  • 2021-01-26 01:18

    The code in the first snippet is 100% correct. You have a pointer to const p, which you repoint to something else. All good and in mint condition.

    The second piece of code is ill-formed. You can't modify an object after removing the constness, if original object was const-qualified (which string literal is).

    0 讨论(0)
  • 2021-01-26 01:22

    I believe that this is not UB, because the pointer itself is not const and I'm not modifying the "foo" object.

    This is correct. The pointer is not const so you can change it to point to something else if you want. In this case it won't cause a meory leak but remember that if the pointer points to data allocated with new and it is the only pointer to that data then you need to call delete before reassigning the pointer otherwise you'll have a meory leak.

    Extra question: and removing the constness of pointer? Would be UB?

    It is only UB if you try to modify a const object you removed const from, which you do in this case. Just removing const is okay, and sometimes needed, but you are never allowed to modify the object unless it was not const to begin with. For example the following is legal since foo is not const.

    int foo = 42;
    
    void bar(int const& baz) { const_cast<int&>(baz) = 21; }
    
    int main()
    {
        bar(foo);
    }
    

    on the other hand

    const int foo = 42;
    
    void bar(int const& baz) { const_cast<int&>(baz) = 21; }
    
    int main()
    {
        bar(foo);
    }
    

    is not legal as foo is const

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