Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::make_shared perform value initialization (GCC and clang disagree)?

Tags:

What I take to mean can be explained by the following example:

auto p = std::make_shared<int>();

Is the int variable default initialized (thus have garbage value) or value initialized (thus have a value of zero)? I've tested on GCC 5.2 and clang 3.6 with the former doing value initialization and the latter doing default initialization. I'm wondering what does the standard say about this? In my opinion, modern C++ should definitely perform value initialization in this case.

like image 348
Lingxi Avatar asked Sep 25 '15 13:09

Lingxi


1 Answers

Yes.

N3797 20.8.2.2.6

Allocates memory suitable for an object of type T and constructs an object in that memory via the placement new expression ::new (pv) T(std::forward<Args>(args)...)

So, here will be

::new (pv) int(); 

And so on by N3797 8.5.1

The initialization that occurs in the forms

T x(a); T x{a}; 

as well as in new expressions (5.3.4) is called direct-initialization.

The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.

— If the initializer is (), the object is value-initialized.

To value-initialize an object of type T means:

— otherwise, the object is zero-initialized.

And both new clang and GCC agree with the standard: Live

like image 51
ForEveR Avatar answered Sep 21 '22 01:09

ForEveR