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
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.