Reputation: 64356
I'm learning ctors now and have a few question. At these lines:
Foo obj(args);
Foo obj2;
obj2 = Foo(args);
Foo obj3 = Foo(args);
First part: only 1 constructor called (Foo) and obj
is initialized. So, 1 object creation.
Second part: creating of temporary object obj2
, calling default ctor for it. Next lines we create another copy of Foo
and pass its copy into operator=()
. Is that right? So, 3 local temporary objects, 2 constructor callings.
Third part: create 1 object Foo
and pass its copy into operator=()
. So, 2 temprorary objects and 1 ctor calling.
Do I understand this right? And if it's true, will compiler (last gcc, for example) optimize these in common cases?
Upvotes: 14
Views: 44281
Reputation: 46599
Your terminology is a bit confusing.
The objects obj
, obj2
obj3
are not called "temporary objects". Only the instance that is created in line 3 before being assign to obj is a temporary object.
Also, you don't create "a copy of Foo", you create either "an instance of Foo" or "an object of type Foo".
Upvotes: 2
Reputation: 361722
I will comment on the third one first:
Foo obj3=Foo(args);
It doesn't use operator=
which is called copy-assignment. Instead it invokes copy-constructor (theoretically). There is no assignment here. So theoretically, there is two objects creation, one is temporary and other is obj3
. The compiler might optimize the code, eliding the temporary object creation completely.
Now, the second one:
Foo obj2; //one object creation
obj = Foo(args); //a temporary object creation on the RHS
Here the first line creates an object, calling the default constructor. Then it calls operator=
passing the temporary object created out of the expression Foo(args)
. So there is two objects only the operator=
takes the argument by const
reference (which is what it should do).
And regarding the first one, you're right.
Upvotes: 17
Reputation: 88225
Yes, Foo obj(args)
creates one Foo object and calls the ctor once.
obj2
is not considered a temporary object. But just like 1 Foo obj2
creates one object and calls the Foo
ctor. Assuming that you meant obj2 = Foo(args)
for the next line, this line creates one temporary Foo object and then calls obj2.operator=()
. So for this second example there is only a single temporary object, a single non-temporary, Foo ctors are called twice (once for the non-temporary, once for the temporary) and the operator=() is called once.
No, this line does not call operator=()
. When you initialize obj3
using the =
syntax it is almost exactly as if you had used parentheses instead: Foo obj3(Foo(args));
So this line creates a temporary object, and then calls the Foo copy ctor to initialize obj3 using that temporary object.
Upvotes: 4