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?
I will comment on the third one first:
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 isobj3. The compiler might optimize the code, eliding the temporary object creation completely.Now, the second one:
Here the first line creates an object, calling the default constructor. Then it calls
operator=passing the temporary object created out of the expressionFoo(args). So there is two objects only theoperator=takes the argument byconstreference (which is what it should do).And regarding the first one, you’re right.