Creating and creating a C ++ object

Now I am studying ctors and asking some questions. In these lines:

Foo obj(args); Foo obj2; obj = Foo(args); Foo obj3 = Foo(args); 

The first part : only 1 constructor with the name (Foo) and obj initialized. So, creating one object.

The second part : creating a temporary obj2 object that calls ctor for it by default. In the following lines, we create another copy of Foo and pass it to operator=() . It is right? So, 3 local temporary objects, 2 constructor calls.

Third part : create 1 Foo object and pass it to operator=() . So, 2 temporal objects and 1 ctor call.

Do I understand this correctly? And if this is true, will the compiler (the latest gcc, for example) optimize them in normal cases?

+6
source share
3 answers

I will first comment on the third:

 Foo obj3=Foo(args); 

It does not use operator= , which is called copying. Instead, it calls the constructor instance (theoretically). There are no assignments. Thus, theoretically, there are two objects, one of which is temporary, and the other is obj3 . The compiler can optimize the code by fully returning the creation of a temporary object.

Now second:

 Foo obj2; //one object creation obj = Foo(args); //a temporary object creation on the RHS 

Here, the first line creates an object that calls the default constructor. Then it calls operator= passing the temporary object created from the Foo(args) expression. Thus, there are only two objects: operator= takes an argument using a const reference (which should do).

And as for the first, you're right.

+6
source
  • Yes, Foo obj(args) creates one Foo object and calls ctor once.

  • obj2 not considered a temporary object. But just like 1 Foo obj2 creates one object and calls Foo ctor. Assuming you meant obj2 = Foo(args) for the next line, this line creates one temporary object Foo, and then calls obj2.operator=() . Thus, for this second example, there is only one temporary object, one not temporary, Foo ctors is called twice (once for non-temporary, once for temporary), and the = () operator is called once.

  • No, this line does not call operator=() . When you initialize obj3 with the = syntax, it is almost exactly as if you used parentheses instead: Foo obj3(Foo(args)); So this line creates a temporary object and then calls a copy of Foo ctor to initialize obj3 using this temporary object.

+3
source

Your terminology is a bit confusing.

Objects obj , obj2 obj3 not called temporary objects. Only the instance created on line 3 before the obj assignment is a temporary object.

Also, you are not creating a “copy of Foo”, you are creating an “instance of Foo” or an “object of type Foo”.

+1
source

Source: https://habr.com/ru/post/905443/


All Articles