C++ multiple unique pointers from same raw pointer

后端 未结 3 1684
无人及你
无人及你 2021-02-20 12:27

Consider my code below. My understanding of unique pointers was that only one unique pointer can be used to reference one variable or object. In my code I have more than one uni

3条回答
  •  甜味超标
    2021-02-20 12:56

    But still, why is this valid

    It is not valid! It's undefined behaviour, because the destructor of std::unique_ptr will free an object with automatic storage duration.

    Practically, your program tries to destroy the int object three times. First through uniquePtr2, then through uniquePtr1, and then through val itself.

    and not having a compilation error?

    Because such errors are not generally detectable at compile time:

    unique_ptr  uniquePtr1(valPtr);
    unique_ptr  uniquePtr2(function_with_runtime_input());
    

    In this example, function_with_runtime_input() may perform a lot of complicated runtime operations which eventually return a pointer to the same object valPtr points to.


    If you use std::unique_ptr correctly, then you will almost always use std::make_unique, which prevents such errors.

提交回复
热议问题