Reputation: 314
My question is quite simple but, actually, I can't find any information about this. Does copy (move) assignment operator require assignee to be constructed?
Upvotes: 0
Views: 96
Reputation: 73366
The copy constructor, be it in the syntax T object(object_to_copy)
or T object = object_to_copy
construct the new object, so doesn't require that it already exists. This is documented in the C++ standard, section 12.8/2.
The ordinary assignment operator, which is used in other context than copy construction above, does require the target object to already exist (i.e. must be constructed). This can easlily be deduced from section 13.5 of the standard.
Upvotes: 1
Reputation: 16070
On the contrary to the other answers, I will say that the operator=
can be called before the object is constructed. I believe the following code is valid and doesn't provoke undefined behaviour.
#include <iostream>
class A
{
public:
A(){
std::cout << "A()\n";
*this = *this;
}
A(const A& a) { std::cout << "A(const A& a)\n"; }
A& operator=(const A& a) { std::cout << "operator=\n"; return *this; }
};
int main()
{
A a;
return 0;
}
Output:
A()
operator=
Of course it doesn't make any sense. However, the question is whether something is allowed, my answer yes it is. Clearly operator=
is called before the constructor ended and one is allowed to write such a construction.
Upvotes: 0
Reputation: 10723
What I can get from your question is you want to ask whether in a = b
, should a
be fully constructed.
In that case answer is yes, a
should be a fully constructed object before assignment operator is called on that. Because assignment only makes sense between two objects not between object and some random raw bits.
Upvotes: 0