Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization with empty curly braces

First attempt and everything works fine:

class Base {
 public:
    Base() {std::cout << "default ctor!\n"; }
};
...
Base b{};
Base b_one = {};

Another way of implementation(add explicit):

class Base {
 public:
    explicit Base() {std::cout << "default ctor!\n"; }
};
...
Base b{};
Base b_one = {};  // error! Why?

I have read on cppreference that in both cases default initialization would be used and no diffences.

From list initialization:

Otherwise, If the braced-init-list is empty and T is a class type with a default constructor, value-initialization is performed.

From value initialization:

if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;

like image 772
Gusev Slava Avatar asked Aug 15 '18 15:08

Gusev Slava


People also ask

Why initialize with curly braces C++?

The code above shows how curly braces can be used to declare various types of variables and assign values to them. Using curly braces instead of an = sign is one of the many ways to initialize. Using curly braces to initialize a variable also prevents narrowing.

What do empty brackets mean in C++?

What do empty brackets mean in struct declaration? T object {}; is syntax for value initialization (4). Without the curly brackets, the object would be default initialized. To be pedantic, this is not a "struct declaration". It is declaration of a variable.

What is brace initialization?

If a class has non-default constructors, the order in which class members appear in the brace initializer is the order in which the corresponding parameters appear in the constructor, not the order in which the members are declared (as with class_a in the previous example).

What is a {} in CPP?

{} uses list initialization, which implies value initialization if the braces are empty, or aggregate initialization if the initialized object is an aggregate. Since your X is a simple int , there's no difference between initializing it with () or {} .


1 Answers

I have read on cppreference that in both cases default initialization would be used and no diffences.

No they're not the same. To be precise, Base b{}; is direct-list-initialization, while Base b_one = {}; is copy-list-initialization; for copy-list-initialization, only non-explicit constructor may be called.

(emphasis mine)

  • direct-list-initialization (both explicit and non-explicit constructors are considered)

  • copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)

like image 176
songyuanyao Avatar answered Oct 29 '22 08:10

songyuanyao