Reputation: 34316
The rule-of-three is well known and says that if one has to define a destructor, so one has most probably to define a copy constructor and an assignment operator.
However, recently in some code, I stumbled upon a "rule-of-two": Only the destructor and the copy constructor were defined and the assign operator was left for compiler to define. My first thought was "this must be an error", but now I'm not that sure, because all compilers (gcc, msvs, intel) produced assignment operator which called the copy constructor.
Simplified, the class looks as follows:
struct A{
size_t size;
int *p;
A(size_t s): size(s), p(new int[size]){}
A(const A&a): size(a.size), p(new int[size]){
std::copy(a.p, a.p+a.size, p);
std::cout<<"copy constructor called\n";
}
~A(){
delete[] p;
}
};
And used like this:
int main(){
A a(2);
a.p[0]=42.0;
A b=a;
std::cout<<"first: "<<b.p[0]<<"\n";
}
produces the following output:
copy constructor called
first: 42
My question: It is guarantied, that the compiler defined assignment operator will call the copy constructor, or it is only a lucky coincidence, that all compilers do it that way?
Edit: It's true, I confused initialization and assignment! Replacing A b=a;
by A b(0); b=a
leads as expected to a double-free-error.
Upvotes: 3
Views: 143
Reputation: 76245
Initialization create a new object:
A a; // initialization
A b(a); // initialization
A c = a; // initialization
Assignment modifies an existing object:
A a;
a = 3; // assignment
In the code example, as various comments have said, there is no assignment being done; all of the examples are initializations, so the compiler-generated assignment operator is not used.
Upvotes: 2
Reputation: 409166
It's you who misunderstands what's happening, there is no assignment at all going on, only construction and initialization.
When you do
A b = a;
there's no assignment, only initialization. More precisely copy initialization. It's the same as writing
A b(a);
Upvotes: 5