c++pointerstemporaryvalue-initialization

How to create a temporary value initialized T * in Standard-C++


How to create a temporary value-initialized T* in standard C++?

void foo( int );
void bar( int * );

int main()
{
    foo( int() );  // works. a temporary int - value initialized.
    bar( ??? );    // how to create a temporary int *?
}

Just out of curiousity.


Solution

  • The easiest is to use curly braces:

     bar({});
    

    Or a using statement:

    using p = int*;
    bar( p() );    // how to create a temporary int *?
    

    sehe just reminded me of the stupidly obvious answer of nullptr, 0, and NULL.

    bar(nullptr);
    

    And I'm sure there's many more ways.

    GCC lets you use compound literals, but technically this isn't allowed

     bar((int*){});
    

    http://coliru.stacked-crooked.com/a/7a65dcb135a87ada