Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniform initialization of int*: how can it be forced?

The following code doesn't compile with clang++ 3.8.0 and g++ 6.3.0 (compiler flags are -std=c++11 -Wall -Wextra -Werror -pedantic-errors):

int main()
{
    int* a = int*{}; // doesn't compile
    //       ^^^^ can't be parsed as a type
    (void)a;

    using PInt = int*;

    PInt b = PInt{}; // compiles successfully
    //       ^^^^ is parsed as a type
    (void)b;
}

Is it a way to force int*{} be interpreted by the compiler in the right way here (typedefing of int* is one of such ways)?

like image 957
Constructor Avatar asked Apr 14 '17 16:04

Constructor


1 Answers

You have a few options.

One, which you already discovered, is a type alias:

using PInt = int*;
PInt a = PInt{};

The other is to avoid the completely pointless copy-initialisation:

int* a{};
PInt a{};

The best is to stop wasting time on this fool's errand, and initialise your pointer in a clear manner:

int* a = nullptr;

Of course, that doesn't help you if your question is really about creating a temporary for use in an expression, rather than a full declaration (it isn't clear); but then you have a simple C-style (int*)nullptr to play with.

The short answer, though, is no you cannot "force" a compiler to ignore C++'s grammar and instead use some other grammar.

like image 71
Lightness Races in Orbit Avatar answered Nov 15 '22 03:11

Lightness Races in Orbit