I know this question might seem very very basic. But I just can't find anywhere an example of a move constructor with no pointers.
I have a class that holds a vector object variable. Not a pointer to one. So my question: Does this mean that I have no need in a move constructor? Or is my implementation wrong and I should be using a pointer to a vector and then use a move constructor?
Thank you
If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.
A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying.
Move constructor moves the resources in the heap, i.e., unlike copy constructors which copy the data of the existing object and assigning it to the new object move constructor just makes the pointer of the declared object to point to the data of temporary object and nulls out the pointer of the temporary objects.
It's faster because moving allows the source to be left in a invalid state, so you can steal it's resources. For example, if a object holds a pointer to a large block of allocated memory, a move can simply steal the pointer while a copy must allocate its own memory and copy the whole memory block.
If your class contains movable objects (such as a vector), then just let the compiler generate the implicit move operations. They will do the right thing, moving each subobject.
You'll only need to write your own if you're juggling raw pointers to dynamic objects, or other unmanaged resource handles, yourself. The best approach is to have a correctly copyable/movable object (such as a container, smart pointer, or other RAII class) to manage each of these; then a complex object built by composing these will implicitly have the correct copy/move semantics.
(As noted in the comments: if your class declares its own destructor, or copy operations, then it won't get implicit move operations; you'll need to define your own. But if you follow the advice above, composing it from correctly managed types that don't need any special handling, then you shouldn't need to declare any of these things.)
Move constructor follows similar guidelines as copy constructors. It is required when your class holds members by pointer or other fragile data fields (sockets, db connections etc), so that automatically generated one would possibly mess up the memory layout by deleting the same object twice. So if you don't have any pointer fields, you don't have to write move constructor.
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