Reputation: 473
Currently i am thinking about storing some member objects in unique_ptr. Normally i use unique_ptr just in some functions and move it around, or pass references to it. So how should i do in classes?
Class MyClass {
std::unique_ptr<MyMemberClass> member;
}
or:
Class MyClass {
MyMemberClass member;
}
The lifetime of the object is the same. The initialization in the constructor would be nearly the same. The only difference is, that i can't copy the unique_ptr, or?
Are there other differences? And which should i use or prefer?
Upvotes: 2
Views: 2080
Reputation: 27365
Are there other differences? And which should i use or prefer?
Yes.
The deciding factors here are:
polymorphic behavior : If you store the common interface for a class hierarchy, then you should store by pointer, smart pointer or reference.
lifetime : as you mentioned, if the held object has a longer lifetime than MyClass
(and obviously, it is not owned by MyClass
) then it should be held in a raw pointer or a std::shared_ptr.
ownership : if the object is not owned by MyClass
, then it should be stored as a pointer (smart or not) or a reference.
api constraints: if the held object is generated by a library that can only allocate it dynamically (for example), then you will probably want to hold it in a pointer (or unique_ptr).
When the object is owned (exclussively) by MyClass
, it has the same lifetime as the owning class, and you do not have polymorphic behavior, you should probably store the instance directly.
Upvotes: 3
Reputation: 55897
Differences:
1) You can't copy class with unique_ptr
(you can actually, but this has no sense), but you can move.
2) If member
is unique_ptr
, MyMemberClass
object should be allocated on heap, when in second case it's allocated on stack (when object of type MyClass
is allocated on stack).
3) If member
is complicated object, than probably store pointer on it is better, in other case just object is fine.
4) If member
is unique_ptr
it can be a polymorphic object. It allows to create an aggregate object. With the second form it is not possible (thanks to chmike).
Upvotes: 0