Variables of built-in types can be value-initialized like this:
int var = int();
this way I get the default value of int
without hardcoding the zero in my code.
However if I try to do similar stuff for a pointer:
int* ptr = int*();
the compiler (Visual C++ 10) refuses to compile that (says type int unexpected
).
How do I value-initialize a pointer in similar manner?
You cannot. The syntax
T()
is defined in 5.2.3/1,2 (C++03, slightly different wording in C++11 FDIS). In particular the second paragraph states:That means that
int()
, will create an rvalue of type int and value-initialize it. Now the problem is thatint*
is not a simple-type-specifier, but rather an elaborated-type-specifier. The definition of simple-type-specifier in the grammar is:With type-name being defined as:
This is what makes the proposed solutions work. The creation of the typedef (either directly or through the template) creates a type-name (third type) that can be used as a simple-type-specifier (first type).
Doesn't require the use of
typedef
(but exclusive to C++11), which can be useful when dealing with several pointer types:then
alias<int*>
isint*
, so you can doint* p = alias<int*>()
.A similar solution available to C++03, using an identity metafunction:
Here's one way:
Use a typedef to make a name for your pointer type:
The same idea should work for other types that require more than one lexical element (word) to define the name of the type (e.g.,
unsigned long
,long long
,unsigned long long *
, etc.).This is how you do it int* ptr = new int;
Heap pointers
Just do
It still assigns 0 to the pointer making it point to the NULL address since you're defaulting it with the default value of int which is 0 anyway.
Actually, it works fine for all types:
The address is still a 32-bit (or 64-bit depending on platform) integer so I think it should work fine for all types if you do = int().