When does it make sense to replace "class_name obj_name = func ()" with "class_name obj_name {func ()}"?

In the code, I see the following construction:

const class_name obj_name{func()};

func () returns a class object class_name. So, I wonder why not use the following construction:

const class_name obj_name = func();
+5
source share
2 answers
const class_name obj_name{func()};

Writing down the above, the author tries to adhere to a single initialization syntax (introduced by C ++ 11) to avoid problems caused by annoying analysis and the most unpleasant analysis, in which even experienced programmers fall into the trap by accident. He is trying to incorporate best practice into his brain so that he does not fall into the trap of the parsing issues mentioned, as explained below.

Consider this,

struct X { /*....*/ }; // some class

struct Y 
{
    Y();
    Y(int i);
    Y(X x);
};

Now you can write this:

Y y(100); // declare an object y of type Y

, . !

:

Y y(); 

(), , . , . y, y. vexing parse ++.

, (),

Y y(X());

, , X, " ". , . y, ( , X), y. ++.

, , :

Y y1{};      // invokes 1st constructor
Y y2{100};   // invokes 2nd constructor
Y y3{X{}};   // invokes 3rd constructor

,

Y { function_call() }; 

const class_name obj_name { func() }; // taken from your question!

, , , ?

, .

+5

++ 11 , .

class_name(class_name const&) copy ( ). . .

, {} : initialization_list , , .

, Most Vexing Parse ( , ), , , :

typename class_name obj_name(func());
class_name obj_name { func() };
+1

All Articles