如何在标准 C++ 中创建临时值初始化 T *

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

如何在标准 C++ 中创建临时值初始化 T*

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

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

只是出于好奇。

最简单的是使用花括号:

 bar({});

using语句:

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

sehe 只是让我想起了 nullptr0NULL.

的愚蠢显而易见的答案
bar(nullptr);

我相信还有很多方法。

GCC 允许您使用复合文字,但从技术上讲这是不允许的

 bar((int*){});

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

为了好玩,你可以试试 typedef:

#include <iostream>
void foo( int ) {}
typedef int* PtrInt;
void bar( PtrInt p ) 
{
   std::cout << "The value of p is " << p;
}

int main()
{
    foo( int() );  
    bar( PtrInt() );  
}

实例:http://ideone.com/sjOMlj

为什么不简单地使用这样的东西:

int i=0;
bar(&i);  // safe to dereference in bar()

或者您正在寻找内衬?如果是这样,您可以使用一些令人不快的转换,但是 bar() 实际上不应该 取消引用 那个指针:

bar((int*)0); // or use nullptr if your C++ compiler is more recent