Unified initialization int *: how can this be forced?

The following code does not compile with clang ++ 3.8.0 and g ++ 6.3.0 (compiler flags -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 this a way to get int*{}the compiler to interpret correctly here ( typedefing int*is one such way)?

+4
source share
3 answers

You have several options.

The one you already discovered is an alias of type:

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

Another is to avoid completely pointless copy initialization:

int* a{};
PInt a{};

It’s best to stop wasting time on this insane errand and clearly initialize your pointer:

int* a = nullptr;

, , , ( ); C- (int*)nullptr .

, , , "" ++ - .

+8

:

int* a = (int*){};

, , C99, gcc clang ++ .

decltype(variable_name) , , :

int* a = decltype(a){};

typedef using .

[live demo]

0
template <typename T>
using identity = T;

int main()
{
    int* c = identity<int*>{};
    (void)c;
}
0
source

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


All Articles