Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL containers and non copyable (and non movable) objects

Tags:

c++

stl

Since STL containers require that all contents be copyable and assignable, what is the prefered idiom when working with non copyable objects?

I can think of two different approaches:

  1. Store (smart) pointers rather than the objects in STL containers.

  2. Get rid of STL containers and implement my own lists (e.g. each object must include a pointer to the next object).

Main drawback of the second approach is implementation of destructors (should the "next" object be destroyed before the current one in a recursive way?)

like image 603
jbgs Avatar asked Apr 16 '13 10:04

jbgs


People also ask

What is an STL container?

An STL container is a collection of objects of the same type (the elements). Container owns the elements. Creation and destruction is controlled by the container.

What are the various types of STL containers?

Types of STL Container in C++ In C++, there are generally 3 kinds of STL containers: Sequential Containers. Associative Containers. Unordered Associative Containers.


1 Answers

Since STL containers require that all contents be copyable and assignable, what is the prefered idiom when working with non copyable objects?

Well, actually with C++11 they require the object to be Movable. Only certain operations require them to be Assignable thanks to emplace_* methods.

I can think of two different approaches:

  1. Store (smart) pointers rather than the objects in STL containers.

  2. Get rid of STL containers and implement my own lists (e.g. each object must include a pointer to the next object).

The two approaches are certainly feasible.

In C++11, the STL containers with std::unique_ptr<YourObject> elements in probably the best option. It's standard all the way down. There might be a slight performance issue with the node-based containers since the node and the element they point to will be distinct memory areas; but it's generally imperceptible.

If it is perceptible, or if you cannot use C++11, then you should learn about intrusive containers, which consist in augmenting your objects with hooks so that they can arrange themselves into lists, for example. There is a Boost library for this, obviously: Boost.Intrusive.

Non Movable you said ?

I would honestly challenge most of the designs that argue that an object should not be moved. The only issue with moving is linked to object identity and the potential issues of invalidating pointers to the object being moved from (and thus living dangling pointers behind). This can generally be solved by smart pointers and/or Factory approaches.

like image 52
Matthieu M. Avatar answered Nov 16 '22 01:11

Matthieu M.