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;
}
static_casttoconst int&:test = static_cast<const int&>(3);- rahnema1