Reputation: 24750
I have been doing this for my std::vector
of unique_ptr
s:
m_stuff.push_back(std::unique_ptr<Thing> (new DerivedThing()));
This gives me that automatic memory deletion when elements in the vector are removed.
I have another scenario whereby something else creates the heap memory via new
and thus a generic pointer already exists. Now, suppose I do this:
m_stuff.push_back(std::unique_ptr<Thing> (thingy));
//thingy is Thing*
Can I safely assume that as soon as I do this, my vector m_stuff
now has control over thingy
such that when it is removed from the vector, it is delete
d? Of course, there is the possibility of a dangling pointer if thingy
was copied or stored elsewhere but that is a different issue.
Upvotes: 0
Views: 114
Reputation: 24576
Short answer: yes.
Longer answer: You should store any pointer you create by allocating memory immediately into a smart pointer. Or put otherwise: (Almost) never use plain new
, except in C++11 unique_ptr
initialization. For shared_ptr
there is make_shared
, and in C++14 there will be make_unique
.
Corollary: Don't do this. std::unique_ptr<Thing> (thingy)
is wrong, either because you did not manage thingy
's memory in smart pointers from the beginning (then you should fix that), or because thingy
does not own the object, i.e. it is just a plain referencing pointer and you are not allowed to steal someone elses ownership to pass it to the unique_ptr
. You will get UB when both the unique_ptr
and the real owner try to destroy the object.
Upvotes: 3
Reputation: 24846
unique_ptr
has nothing magical in it. It has jus a regular constructor (actually it has a few) that takes a pointer of type T
and becomes responsible for deleting the pointee. So yes, it does not care (and can't care) where did this pointer came from
Upvotes: 1
Reputation: 476980
Yes, that's right. Once constructed from a raw pointer, the unique pointer owns the pointee.
Upvotes: 0