Reputation: 4264
What would be the difference between a unique_ptr<list<Struct>>
and a list<unique_ptr<Struct>>
? Will list<unique_ptr<Struct>>
result in the memory for the elements to be automatically managed as well?
Upvotes: 0
Views: 128
Reputation: 4303
list<unique_ptr<Struct>>
at the point of construction, whereas when you construct unique_ptr<list<Struct>>
it can just be a nullptr
list<unique_ptr<Struct>>
has an negligible overhead of storing all the pointers unique_ptr<list<Struct>>
would have an overhead when fetching any membersBoth store data on the heap and unique_ptr<list<Struct>>
is a little smaller on the stack.
Upvotes: 1
Reputation: 25647
Saying unique_ptr<>
is like saying *
but with the added benefit of automatic deletion.
The difference between unique_ptr<list<Struct>>
and list<unique_ptr<Struct>>
is exactly the same as the difference between list<Struct>*
and list<Struct*>
. That is, one is a pointer to a list
of Struct
, and the other is a list
of pointers to Struct
. This is a rather obviously major difference.
The list
type manages its own contents, in as much that it allocates memory for the list nodes that hold what you put in the <>
. So a node in a list<Struct>
holds a Struct object directly. But a node in a list<Struct*>
holds only the pointer to the struct.
By logical extension, nodes in list<unique_ptr<Struct>>
hold a unique_ptr<Struct>
, which points to a Struct that has been allocated separately. Conversely, a unique_ptr<list<Struct>>
is a pointer to a list
whose nodes are directly-held Struct
s.
The management of the contents of the list
do not, and can not be handled by a pointer that wraps it. This is a confusion of where management is performed: list
manages its contents - a list - directly, and unique_ptr
manages its contents - a raw pointer - directly, and nothing else.
Upvotes: 2