Reputation: 1262
There's something I don't understand about how the assignment operator works, please have a look at this piece of code:
#include <iostream>
using namespace std;
class foo
{
int val{};
public:
foo()
{
}
foo( int n )
{
val = n;
cout<<"Constructor"<<endl;
}
foo( const foo& f )
{
cout<<"Copy constructor, val "<<endl;
val = f.val;
}
foo( const foo&& f )
{
cout<<"Copy constructor -rvalue-"<<endl;
val = f.val;
}
foo operator+( const foo& other ) const
{
cout<<"Sum "<<endl;
foo foo2;
foo2.val = val + other.val;
return foo2;
}
foo& operator=( const foo& f )
{
cout<<"Assignment operator\n";
val = f.val;
return *this;
}
foo& operator=( const foo&& f)
{
cout<<"Assignment operator, r-value\n";
val = f.val;
return *this;
}
~foo() {}
};
int main()
{
foo a{1}, b{5}, c{4};
foo d;
d = a + b + c;
foo d2 = a + b + c;
return 0;
}
The output of this application is:
Constructor
Constructor
Constructor
Sum
Sum
Assignment operator, r-value
Sum
Sum
What is not clear to me is why the second assignment trigger no assignment operator. The first assignment is on an object which was constructed via the default construction and then a plain assignment operation is visible, in the second one a temporary object should be builded by the compiler and then assigned to d2, but no print are visible from any of the assignment operators provided. Why?
Thanks
Upvotes: 0
Views: 207
Reputation: 1078
For efficiency's sake, this:
foo d2 = a + b + c;
(and any T n = expr
where T
is a type with a non-explicit copy constructor) is actually synonymous for
foo d2(foo(a + b + c)); // can be optimized to foo d2(a + b + c)
not
foo d2;
d2 = a + b + c;
Which is why you only see one assignment in your output.
You can think of it this way: when the variable already exists, it's assignment. When you're creating a new variable, it's a constructor call.
Upvotes: 1
Reputation: 96875
The first is assignment, the second is initialization. And in that case the compiler is allowed to elide the copy or move operations that can occur in such a case.
Upvotes: 0
Reputation: 258698
There's no second assignment, your code has only one assignment. The line
foo d2 = a + b + c;
is copy initialization.
Upvotes: 3
Reputation: 20656
You're initializing d2
, not assigning to it, so the assignment operator isn't called.
Upvotes: 0