Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move semantics for big non-pointer base objects

Tags:

c++

c++11

When I read examples about move semantics and rvalue references, they're using the advantages of rvalue references and move semantics around big objects which wrap pointers e.g. 1 2

For example, they just copy the pointer which is inside the moving object and set it to nullptr. (Move/Swap)

My question is, Do move semantics have any advantage (performance) for objects which don't have pointers but they're big?

class BigClass
{
   int data[BIG_SIZE];
   int a01;
   .
   .
   . many members
   .
   .
   int z99;

public:

   move constructor ?!
};
like image 260
masoud Avatar asked May 24 '13 13:05

masoud


1 Answers

Do move semantics have any advantage for objects which don't have pointers but they're big?

It will not have any advantage in terms of performance, because you won't be able to quickly "steal the guts" of the object being moved from, as you've noticed.

However, from the purely logical perspective, the semantics of your class may be such that your object is not supposed to be copyable, and therefore a copy-constructor cannot/should not be provided.

For instance, the internals of a unique_ptr are not anything that could be moved any faster than it could be copied (it's a zero-overhead wrapper over a raw pointer), but semantic constraints make it impossible to copy a unique_ptr. In this context, move semantics is all about keeping the invariant that only one unique_ptr pointing to a certain object must exist at a certain time in your program.

Therefore, the move constructor (or move assignment operator) of the unique_ptr also has to reset the pointer being moved from to keep the invariant.

Your class may be something completely different from a unique_ptr, and perhaps considerably heavier, but there may still be semantic constraints that make it non-copyable. In that case, move semantics can be exploited to enforce the correct invariants.

like image 56
Andy Prowl Avatar answered Nov 06 '22 08:11

Andy Prowl