Is it possible to initialize a C ++ object this way?

Possible duplicate:
constructor call mechanism

Suppose a class ABC then:

1) Is the following initialization possible? If so, what are the detailed steps:

  ABC a( ABC() ); 

2) What is the difference (performance, etc.) between these two forms of creating an object?

 ABC a; ABC b=ABC(); 
+4
source share
3 answers
  ABC a( ABC() ); 

Declares a function with the name a , which takes an object of type a pointer to a function that returns an ABC object and does not accept arguments. There is no object creation.

 ABC a; 

Creates an object of type ABC , invoking the default constructor.

 ABC b=ABC(); 

Creates a temporary object of type ABC , and then calls the copy constructor to copy this object to b .
It is important to note that the compiler can omit the copy constructor invocation here, using optimization of the return value.

+1
source

1) As written, this is a function declaration; you need to modify it a bit to get the behavior you plan:

 ABC a((ABC())); 

or

 ABC a = ABC(); 

In this case, the compiler has two options:

  • Create a temporary object using the default constructor and initialize a using the copy constructor;
  • Return the copy and create a using the default constructor.

In both cases, there must be an available copy constructor, even if it is not actually used.

2)

 ABC a; 

This will create a using the default constructor.

 ABC b = ABC(); 

This will do the same as in question 1; it is up to the compiler whether to delete the copy.

Thus, the first form could potentially be more efficient if the compiler does not perform this particular optimization, and if copying the default initialized object is expensive.

+1
source

1) first creates an ABC instance (internal, the constructor is called without any parameter) and passes this (temporary !!!) instance into the copy ABC constructor . It is absolutely useless if the copy constructor does what it should.

2) declares a variable with the name a and at the same time initializes it using the constructor with no arguments ( default constructor ). Both versions of ins 2) are absolutely equal.

-2
source

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


All Articles