Initializing a C ++ 11 value using a standard default constructor

In the following example:

#include <iostream> struct A { int z; A(std::string) {} A() = default; }; int main() { char buf[1000]; std::fill(buf, buf + 1000, 'x'); auto a = new(buf) A{}; std::cerr << "Az: " << a->z << std::endl; } 

Compiled with GCC 4.8 prints zero (same behavior with Clang 3.4). This seems to indicate that a initialized to zero before calling the default constructor.

But according to the value initialization rule on cppreference.com , an object should not be initialized before calling the default constructor. Class a is suitable for bullet point # 1 in C ++ 11:

1) If T is a class type with at least one user-supplied constructor of any type, the default constructor is called.

Another useful data point is that if we replace A() = default with A() {} in the above example, no zero-initialization does expected. This, apparently, indicates that in the original example the error No. 2 of initializing the value is executed, which would be incorrect:

2) If T is a type of non-unit class without any user-created constructors, then the object is initialized to zero, and then the implicitly declared default constructor is called (unless it is trivial)

+6
source share
1 answer

The wording that you specified to initialize the value in C ++ 11 was considered defective, see DR 1368 Main Working Group and resolution in DR 1301 Main Working Group , which changed the wording (showing additions in bold and deletions with a bump through ):

To initialize an object with type T means:

  • if T is (possibly cv-qualit) a class type (section 9 [class]) with either a default constructor (12.1 [class.ctor]), or a default user-created constructor or a remote constructor (12.1 [class.ctor] ) , then the object is initialized by default with the default constructor for T (and initialization is poorly formed if T does not have an available default constructor) ;

  • if T is a (possibly cv-qualified) class of non-union type without a user-supplied constructor or is deleted by default , then the object is initialized to zero and if T is an implicitly declared default constructor, T has a non-trivial default constructor , which is called by the constructor. default-initialized ;

Some compilers - I believe that GCC 4.8 and clang with 3.3ish - have already implemented DR 1301 resolution.

+4
source

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


All Articles