Explicitly select copy assignment

  • A+

In C++11 if both copy and move assignment are available, the compiler automatically chooses copy assignment if the argument is lvalue and move assignment if it is rvalue. Using std::move it is possible to explicitely select the move assignment for lvalue. But how is it possible to explicitely select the copy assignment for rvalue?

Code example:

#include <iostream>  class testClass { public:     testClass &operator=(const int &other) {         std::cout << "Copy assignment chosen." << std::endl;         return *this;     }      testClass &operator=(int &&other) {         std::cout << "Move assignment chosen." << std::endl;         return *this;     }    };    int main(int argc, char *argv[]) {     int a = 4;     testClass test;      test = a; // Selects copy assignment     test = 3; // Selects move assignment      test = std::move(a); // Selects move assignment //  test = std::copy(3); // <--- This does not work      return 0; } 


One possible way is to write your own copy to bind the object to an lvalue reference:

template <class T> constexpr T& copy(T&& t) {     return t; } 

And you can test it this way:

test = copy(a); test = copy(3); test = copy(std::move(a)); 

You may put this function in your own namespace to keep things clean.

To address fear of lifetime issue, here is some considerations:

  • This copy function takes a reference and returns the same reference immediately. It implies that the caller is responsible for controlling the lifetime.
  • Lifetime of a temporary object persists until the end of the statement. This makes the object persists long enough to be passed into the left hand side of =.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: