Std Vector Move Assignment Operator

A move assignment operator of class is a non-template non-static member function with the name operator= that takes exactly one parameter of type T&&, const T&&, volatile T&&, or constvolatile T&&.

[edit]Syntax

class_nameclass_name ( class_name ) (1) (since C++11)
class_nameclass_name ( class_name ) = default; (2) (since C++11)
class_nameclass_name ( class_name ) = delete; (3) (since C++11)

[edit]Explanation

  1. Typical declaration of a move assignment operator.
  2. Forcing a move assignment operator to be generated by the compiler.
  3. Avoiding implicit move assignment.

The move assignment operator is called whenever it is selected by overload resolution, e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.

Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a std::string or from a std::vector may result in the argument being left empty. This is not, however, a guarantee. A move assignment is less, not more restrictively defined than ordinary assignment; where ordinary assignment must leave two copies of data at completion, move assignment is required to leave only one.

[edit]Implicitly-declared move assignment operator

If no user-defined move assignment operators are provided for a class type (struct, class, or union), and all of the following is true:

  • there are no user-declared copy constructors;
  • there are no user-declared move constructors;
  • there are no user-declared copy assignment operators;
  • there are no user-declared destructors;
  • the implicitly-declared move assignment operator would not be defined as deleted,
(until C++14)

then the compiler will declare a move assignment operator as an member of its class with the signature .

A class can have multiple move assignment operators, e.g. both T& T::operator=(const T&&) and T& T::operator=(T&&). If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword .

The implicitly-declared (or defaulted on its first declaration) move assignment operator has an exception specification as described in dynamic exception specification(until C++17)exception specification(since C++17)

Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[edit]Deleted implicitly-declared move assignment operator

The implicitly-declared or defaulted move assignment operator for class is defined as deleted if any of the following is true:

  • has a non-static data member that is const;
  • has a non-static data member of a reference type;
  • has a non-static data member that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator);
  • has direct or virtual base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator);
  • has a non-static data member or a direct or virtual base without a move assignment operator that is not trivially copyable;
  • has a direct or indirect virtual base class.
(until C++14)

A deleted implicitly-declared move assignment operator is ignored by overload resolution.

(since C++14)

[edit]Trivial move assignment operator

The move assignment operator for class is trivial if all of the following is true:

  • It is not user-provided (meaning, it is implicitly-defined or defaulted);
  • has no virtual member functions;
  • has no virtual base classes;
  • the move assignment operator selected for every direct base of is trivial;
  • the move assignment operator selected for every non-static class type (or array of class type) member of is trivial;
  • has no non-static data members of volatile-qualified type.
(since C++14)

A trivial move assignment operator performs the same action as the trivial copy assignment operator, that is, makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially move-assignable.

[edit]Implicitly-defined move assignment operator

If the implicitly-declared move assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used.

For union types, the implicitly-defined move assignment operator copies the object representation (as by std::memmove).

For non-union class types (class and struct), the move assignment operator performs full member-wise move assignment of the object's direct bases and immediate non-static members, in their declaration order, using built-in assignment for the scalars, memberwise move-assignment for arrays, and move assignment operator for class types (called non-virtually).

As with copy assignment, it is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator:

struct V { V& operator=(V&& other){// this may be called once or twice// if called twice, 'other' is the just-moved-from V subobjectreturn*this;}};struct A :virtual V {};// operator= calls V::operator=struct B :virtual V {};// operator= calls V::operator=struct C : B, A {};// operator= calls B::operator=, then A::operator=// but they may only called V::operator= once   int main(){ C c1, c2; c2 = std::move(c1);}
(since C++14)

[edit]Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator (same applies to copy assignment).

See assignment operator overloading for additional detail on the expected behavior of a user-defined move-assignment operator.

[edit]Example

Run this code

Output:

#include <string>#include <iostream>#include <utility>   struct A {std::string s; A(): s("test"){} A(const A& o): s(o.s){std::cout<<"move failed!\n";} A(A&& o): s(std::move(o.s)){} A& operator=(const A& other){ s = other.s;std::cout<<"copy assigned\n";return*this;} A& operator=(A&& other){ s = std::move(other.s);std::cout<<"move assigned\n";return*this;}};   A f(A a){return a;}   struct B : A {std::string s2;int n;// implicit move assignment operator B& B::operator=(B&&)// calls A's move assignment operator// calls s2's move assignment operator// and makes a bitwise copy of n};   struct C : B { ~C(){}// destructor prevents implicit move assignment};   struct D : B { D(){} ~D(){}// destructor would prevent implicit move assignment D& operator=(D&&)=default;// force a move assignment anyway };   int main(){ A a1, a2;std::cout<<"Trying to move-assign A from rvalue temporary\n"; a1 = f(A());// move-assignment from rvalue temporarystd::cout<<"Trying to move-assign A from xvalue\n"; a2 = std::move(a1);// move-assignment from xvalue   std::cout<<"Trying to move-assign B\n"; B b1, b2;std::cout<<"Before move, b1.s = \""<< b1.s<<"\"\n"; b2 = std::move(b1);// calls implicit move assignmentstd::cout<<"After move, b1.s = \""<< b1.s<<"\"\n";   std::cout<<"Trying to move-assign C\n"; C c1, c2; c2 = std::move(c1);// calls the copy assignment operator   std::cout<<"Trying to move-assign D\n"; D d1, d2; d2 = std::move(d1);}
Trying to move-assign A from rvalue temporary move assigned Trying to move-assign A from xvalue move assigned Trying to move-assign B Before move, b1.s = "test" move assigned After move, b1.s = "" Trying to move-assign C copy assigned Trying to move-assign D move assigned

Default constructor

Stop trying to save space like that. THe point of good coding is to make it readable by humans. The computer can read any style so try and make it more maintainable by making it readable.

I would write it like this:

Sure you can use for the zero sized array. But this seems like a premature optimization. You can make the rest of your code less complicated by never having a null . If there is never a null then your code does not need to check for it.

Also currently you have different behavior for:

Constructor

Print

Sure this works. But is not the only stream you way want to print too

So I would pass a stream to . It can default to . Then you should add an . As the normal way of printing something is via .

Note: prefer to . The difference is a stream flush. The stream will already flush itself when required. So you adding extra flushes is only going to cause the flushes to be less optimal.

Copy Constructor

Move constructor

Yes that works. But you should also mark the move constructor as . The standard containers have optimizations that can be applied if they know tour class will not throw when being moved. Otherwise they have to fallback to copying to provide the strong exception guarantee.

The standard technique is to use swap though. It makes it look and behave just like move assignment. See below.

Copy Assignment

Yes the test for self assignment looks like a good optimization.

BUT its not. Self assignment happens so rarely (in fact basically never in real code) that what you are doing is pesimizing the normal flow and as a result will make your code slower. You do need to cope with self assignment but because it is so rare you don't need to worry that it is not the optimal path.

The second issue I have here is that you destroy the local data before you have a copy of the new data ready.

If something goes wrong in the rest of your code then you will be unable to roll back the state and thus can not provide the strong exception guarantee. When copying an object it should happen in three distict phases.

So your Copy assignment should look like this:

If you look carefully at those three stages. Stage 1 looks like the constructor and stage 3 looks like the destructor and stage 2 looks like a standard swap function so we can simplify the above to exactly that:

This is called the copy and swap idiom.

Move Assignment

Again the pesimizing test for self assignment.

The standard move assignment is to swap the source and the destination. This has a couple of benefits.

  1. You don't call delete (and thus don't invoke the destructor). Thus it is potentially faster.
  2. Because you did not delete the data there is an opportunity for it to be reused.
  3. If the source is going out of scope it will invoke its destructor and destroy your data but it will be done after the completion of your object thus giving you strong exception guarantee. Thus allowing you to make your assignment operator noexcept.

Standard Move Assignment

I wrote a series of posts about all this.

Vector - Resource Management Allocation
Vector - Resource Management Copy Swap
Vector - Resize
Vector - Simple Optimizations
Vector - the Other Stuff

Re-Write

0 Replies to “Std Vector Move Assignment Operator”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *