提问者:小点点

是否可以默认初始化一个临时变量?


请考虑以下代码:

struct S { int m; };

S trick() { S s; return s; } 

void bar(S s) { /* observe s.m */ }

void foo()
{
    S s;           // s.m is indeterminate
    S* p = new S;  // p->m is indeterminate
    bar(S());      // bar() will observe S::m to be 0
    bar(trick());  // bar() will observe S::m to be indeterminate
}

有没有可能构造一个类型为S的临时变量而不用出花招呢?

我为什么需要这个?

据我所知,“默认初始化”在概念上是构造对象最便宜的方法。 以这种方式构造临时数据的能力对于忽略不需要的数据非常有用,并且开销尽可能小:

struct S { int m; };

void foo(S* pOut);   // 3rd party function that insists on returning some data

template<class T> T* tmp_addr(T&& v) { return &v; }  // careful with this one...

foo( tmp_addr(trick()) ); // receive and discard data without zeroing out memory

共2个答案

匿名用户

是否可以默认初始化一个临时变量?

我可不这么认为。

此外,程序的行为是未定义的,因为它读取(复制)不确定的值。 在不初始化值的情况下使用foo的一个简单而正确的方法是不使用临时的:

S s;
foo(&s);

匿名用户

不如:

#include <memory>

struct Foo 
{
  int i;
};

auto trick() { return std::make_unique<Foo>(); }

void foo(Foo* f);

int main() 
{ 
    foo(trick().get()); 
}

相关问题