I'm reading this answer about move semantic and come up with a problem. He describes the so-called move and swap idiom:
unique_ptr& operator=(unique_ptr source) // note the missing reference
{
std::swap(ptr, source.ptr);
return *this;
}
Since the move assignment operator are supposed to operate on rvalue references, I thought that it's acceptable to pass the rvalue reference as an argument. Here is an example:
#include <iostream>
struct A {
A(){ }
virtual ~A(){ }
A(A&&){ }
};
void foo(A a){
std::cout << "foo(A)" << std::endl;
}
int main()
{
foo(*new A);
}
But the compiler warns me that it tried to copy the referenced object and failed because the copy-constructor is deleted. I don't udnerstand why it's correct in the example with unique_ptr
. The object is supposed to be copied when we invoke the function, so there's no point of move semantic.
Couldn't you explain it a bit?