I'm learning about std::unique_ptr
, trying to grok what it represents.
Given a function (out of my control) that returns a unique_ptr
, is it implied/well understood that each invocation returns a unique_ptr
that points to a new object (different than any prior invocation)?
By way of example, the following code produces a double-free on exit, and I hope that I correctly understand why: unique_ptr
s delete their underlying object on destruction; therefore two unique_ptr
s encapsulating the same memory/object would cause a double-free on destruction of the second. Therefore, would the following implementation of function getUniquePtr()
be commonly/implicitly understood to be unreasonable?
// main.cpp
#include <memory>
#include <iostream>
std::unique_ptr<int> getUniquePtr() {
static int* p = new int(42);
return std::unique_ptr<int>(p);
}
class PtrOwner {
public:
std::unique_ptr<int> p_;
};
int main( int argc, char* argv[] ) {
PtrOwner po1;
PtrOwner po2;
po1.p_ = getUniquePtr();
po2.p_ = getUniquePtr();
return 0;
}
It should be assumed that, if a function returns
std::unique_ptr<T>
, then the returned smart pointer points to an object that is not currently managed by anyone else. This does not necessarily mean that it always refers to a different object. So long as this convention is followed, double-free bugs will be avoided. If this convention is violated, double-free bugs will occur.For example, if you see some function like this:
This function might, potentially, return
std::move(arg)
under some circumstances or it might destroyarg
and return some other pointer. (You have to read the documentation to know what it does). This implies that you could do something like this:In this case,
foo
might just return the same pointer value twice, and this is perfectly safe. This example seems silly, but hopefully it gets my point across.