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 dif
I'd choose approach #1: i.e. store smart pointers to objects in STL containers.
Note that it's fine to store non-owning raw pointers in STL containers (e.g. observing raw pointers), but storing owning raw pointers is a "leaktrocity": use shared_ptr
or new C++11's unique_ptr
instead.
As for #2, writing your own containers from scratch requires lots of time and energy, and I believe you can't match the richness of a full commercial-quality STL library implementation in a reasonable time-frame.
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.