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:
Store (smart) pointers rather than the objects in STL containers.
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?)
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.
Types of STL Container in C++ In C++, there are generally 3 kinds of STL containers: Sequential Containers. Associative Containers. Unordered Associative Containers.
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:
Store (smart) pointers rather than the objects in STL containers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With