R copy semantics
In the we looked at the issues of resource management in C++ and introduced “The Rule of The Big Three (and a half)”. In this article we’ll extend this concept by looking at the idea of move semantics, a feature introduced in C++11. Move semantics mean we’ll have to extend our rule to “The Rule of The Big Five” or, perhaps more correctly, “The Rule of The Big Four (and a half)”.
The cost of copying
Earlier, we had defined a SocketManager class that manages the lifetime of a Socket object. Here’s the type definition for the SocketManager:
The Socket is allocated in the SocketManager constructor; and de-allocated in the destructor.
The SocketManager class implements both the copy constructor and assignment operator, providing a ‘deep copy’ policy. You should read the previous article if you’re not already familiar with the Copy-Swap Idiom I’ve used here.
Copying objects may not be the best solution in many situations. It can be very expensive in terms of creating, copying and then destroying temporary objects. For example:
- Returning objects from functions
- Some algorithms (for example, swap)
- Dynamically-allocating containers.
Let’s take a vector of SocketManagers as an example:
As expected we get the constructor for the (temporary) SocketManager object, then the copy constructor as it is inserted into the vector. The second copy constructor is caused by the vector memory allocator creating space for two new objects then copying the objects across. This is an expensive operation since every copy requires de-allocation / re-allocation of memory and copying of contents.
Here we’re using the default constructor for the SocketManager class. We will discuss the consequences of this later.
For this example I’m deliberately ignoring emplacement of the objects; although the copying will still occur as memory is allocated.
Traffic stats
Willow Tree Inquisitive Child Home (DEMDACO - Home)
|
72 Piece Mini Unit Bricks Architect Set - (Wood Building / Stacking Blocks - Toy for Kids & Children 3 Years & Up) Toy (Unit Bricks)
|
iPhone 6 Ouija Board Case (TPU), for the Spiritually Inquisitive Individuals! Wireless (Bodega on Madison)
|
|
Inquisitive Octopus iPhone 6 Plus Shadow green Tough Phone Case Wireless (FSKcase?)
|
|
being TRUE - Satin Lip Shine - Inquisitive Beauty (beingTRUE)
|