C++11 Completed RAII, Making Composition Easier
The addition of move semantics in C++11 is not just a performance and safety improvement. It’s also the feature that completed RAII. And as of C++11 I believe that RAII is absolutely necessary to make object composition easy in the language.
To illustrate let’s look at how objects were composed before C++11, what problems we ran into, and how everything just works automatically since C++11. Let’s build an example of three objects:
struct Expensive
{
std::vector<float> vec;
};
struct Group
{
Group();
Group(const Group &);
Group & operator=(const Group &);
~Group();
int i;
float f;
std::vector<Expensive *> e;
};
struct World
{
World();
World(const World &);
World & operator=(const World &);
~World();
std::vector<Group *> c;
};
Before C++11 composition looked something like this. It was OK to have a vector of floats, but you’d never have a vector of more expensive objects because any time that that vector re-allocates, you’d have a very expensive operation on your hand. So instead you’d write a vector of pointers. Let’s implement all those functions: