TransWikia.com

Is it possible to default-initialize a temporary variable?

Stack Overflow Asked on November 24, 2021

Consider this code:

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
}

Is it possible to construct a temporary variable of type S without resorting to tricks?

Why do I need this?

As I understand "default initialization" is conceptually the cheapest way to construct an object. Ability to construct a temporary in such way can be useful to ignore data you don’t need with as little of overhead as possible:

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

3 Answers

You can default initialize a sub-object of a temporary variable.

template<typename T>
class default_init_tmp final {
  T t;
  public:
  default_init_tmp () /*Intentionally left blank*/ {}
  default_init_tmp (default_init_tmp const&) = delete;
  void operator=(default_init_tmp const&) = delete;
  T* operator&() { return &t; }
};

Granted, usually it's ill-advised to overload operator&, but it somehow seems appropriate here, given the general nature of the exercise. You'd use it as follows

int main() 
{ 
    foo(&default_init_tmp<S>()); 
}

Answered by StoryTeller - Unslander Monica on November 24, 2021

How about:

#include <memory>

struct Foo 
{
  int i;
};

auto trick() { 
    return std::make_unique_for_overwrite <Foo>(); // C++20
    // return std::unique_ptr<Foo>(new Foo);       // pre C++20
}

void foo(Foo* f);

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

Answered by Ayxan Haqverdili on November 24, 2021

Is it possible to default-initialize a temporary variable?

I don't think so.

Also, the behaviour of your program is undefined, because it reads (copies) indeterminate values. A simple, and correct way to use foo without value initialisation is to not use a temporary:

S s;
foo(&s);

Answered by eerorika on November 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP