Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

Unique_ptr containers or unique_ptr elements

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

Answers (2)

Janek Olszak
Janek Olszak

Reputation: 4303

  • The obvious difference is that you have to define 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 members

Both store data on the heap and unique_ptr<list<Struct>> is a little smaller on the stack.

Upvotes: 1

greyfade
greyfade

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 Structs.

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

Related Questions