Preference when initializing variables in C ++

Run in C ++ and notice that you can initialize a variable in two ways.

int example_var = 3;  // with the assignment operator '='

or

int example_var(3);  // enclosing the value with parentheses 

Is there a reason to use one over the other?

+5
source share
4 answers

The first form goes back to C time, and the second goes back to C ++. The reason for the addition is that in some contexts (in particular, initializer lists in constructors) the first form is not allowed.

, , . , . - .

?

, , .

, , , -- . ( ), , :

std::string s = std::string();  // ok declares a variable
std::string s( std::string() ); // declares a function: std::string s( std::string(*)() )

, ++ 11 , :

std::string s{std::string{}};

, .

?

, . , , , , ...

+6

, int, .
. , .

:

++ ?

+6

... . int , .

+1

They compile to the same thing. However, both are a form of initialization variable, not assignment, which matters a little in C and a lot in C ++, since completely different functions are called (constructor v. Assign).

0
source

All Articles