Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ do value initialization of a POD typedef?

Tags:

c++

pointers

Does C++ do value initialization on simple POD typedefs?

Assuming

typedef T* Ptr;

does

Ptr()

do value-initialization and guarantee to equal (T*)0?

e.g.

Ptr p = Ptr();
return Ptr();
like image 518
Neil Gall Avatar asked May 25 '09 13:05

Neil Gall


1 Answers

It does. For a type T, T() value-initializes an "object" of type T and yields an rvalue expression.

int a = int();
assert(a == 0);

Same for pod-classes:

struct A { int a; };
assert(A().a == 0);

Also true for some non-POD classes that have no user declared constructor:

struct A { ~A() { } int a; };
assert(A().a == 0);

Since you cannot do A a() (creates a function declaration instead), boost has a class value_initialized, allowing to work around that, and C++1x will have the following, alternative, syntax

int a{};

In the dry words of the Standard, this sounds like

The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized

Since a typedef-name is a type-name, which is a simple-type-specifier itself, this works just fine.

like image 116
Johannes Schaub - litb Avatar answered Oct 03 '22 10:10

Johannes Schaub - litb