class A
{
public:
A ()
{
wcout << L"Empty constructed." << endl;
}
A (LPCWSTR Name)
: m_Name(Name)
{
wcout << L"Constructed." << endl;
}
friend void swap (A& Lhs, A& Rhs)
{
using std::swap;
swap(Lhs.m_Name, Rhs.m_Name);
}
A (A&& Other)
{
wcout << L"Move constructed." << endl;
swap(*this, Other);
}
A (const A& Other)
: m_Name(Other.m_Name)
{
wcout << L"Copy constructed." << endl;
}
A& operator= (A Other)
{
wcout << L"Assignment." << endl;
swap(*this, Other);
return *this;
}
~A ()
{
wcout << L"Destroyed: " << m_Name.GetString() << endl;
}
private:
CString m_Name;
};
int
wmain ()
{
A a;
a = A(L"Name"); // Where is the construction of this temp object?
return 0;
}
This is the output I get for the above code:
Empty constructed.
Constructed.
Assignment.
Destroyed:
Destroyed: Name
See the line with the comment. What I expected is for a temp object to get constructed there, and the argument Other in the operator= would get move-constructed from that temp-object. What’s happening here?
The output that says “Constructed” is actually the feedback from the construction of that temporary object.
If you are looking for an additional copy-construction (or move-construction) of
Otherparameter of copy-assignment operator, it was probably eliminated by copy elision. YourA(L"Name")is immediately constructed and used as thatOtherparameter. No extra copying (or moving) is performed.