Reputation: 25516
Assuming the following code:
T* t = new T();
std::unique_ptr<T> p1(t);
std::unique_ptr<T> p2(t);
Obviously, now two std::unique_ptr
s point to one and the same object. Is this state per se already undefined behaviour? I couldn't find appropriate hints in the standard, so I would answer 'no' so far, but want to get re-assured.
Side note: This question is not about undefined behaviour yielded by double deletion later on, which could be avoided by one of the pointers release()
ing its content at the right time...
Edit:
As from comments and answers given arising, too, such multiple ownership is dangerous and should not be applied in real code, even if undefined behaviour actually can be avoided! This question treats a thought experiment only!
Upvotes: 1
Views: 2154
Reputation: 1
According to cppreference, unique_ptr
does not have copy constructors nor assignment operators just for the sole purpose of making sure assigning one unique_ptr
to another ensures both cannot own it at the same time. The definition of constructor 2 states that unique_ptr(pointer p)
shall take a raw pointer to construct itself.
Why doesn't constructor 2 take pointer by reference or use a pointer to pointer? This way it could ensure it has exclusive ownership of that object by setting the pointer given to it to nullptr
. My guess is, because there are still ways to violate unique ownership rules such as making 2 pointers point to an object and passing one of them to the constructor but still have a raw pointer to the object. Because the class cannot control what is going on in the outside world it can only maintain the rules for itself.
Upvotes: -1
Reputation: 180500
Technically there is no UB until you do something that causes a double delete. The constructor of std::unique_ptr
does not state that the pointer should not already be owned, so in the strictest sense of the word it is not undefined behavior to have the pointer owed by two object
That said, semantically the code is not correct and this should not be done. You are breaking the unique ownership guarantee that std::unique_ptr
provides which means you have to be very careful how you use these objects so that you don't wind up in a double deleted state.
Upvotes: 5