1

I have something like this in my CPP file to initialize an object outside any class. I've simplified it but the point is there is some complex initialization going on but I want a single instance created:

static MyBigObject o = []()
{
  MyBigObject ret;
  ret.Init();
  return ret; 
}();

My question is, does this object get copied from ret to o or created in-place due to compiler cleverness? There might be a proper term for "created in place" - emplaced?

I am working in C++17, if it's pertinent (i.e. the answer depends on language version). Is there a definite answer, or could this be a compiler-specific optimisation?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 1
    In short: almost certainly optimized. In long: https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization – StoryTeller - Unslander Monica Mar 01 '21 at 13:14
  • FWIW, since C++11, if the operation is not elided, then the returned value will be moved if there is a move constructor. – NathanOliver Mar 01 '21 at 13:18
  • *created in-place due to compiler cleverness?* -- If the compiler is clever enough to do it, it will do it. Why would it waste the opportunity? Also, C++ compilers from way back even before standardization in 1998 did all sorts of tricks to optimize and outdo competing C++ compilers. – PaulMcKenzie Mar 01 '21 at 13:18
  • It depends on what operations (move constructors, etc) `MyBigObject` supports. But, in this case, the problem can be eliminated by having the default constructor of `MyBigObject` do all the "complex initialization" needed, rather than waiting for a member function `Init()` to be called after the constructor completes. Then the definition of the instance can simply be `MyBigObject o;` – Peter Mar 01 '21 at 13:29

1 Answers1

2

In this case: this depends on your compiler. This is named return value optimization, which is optionally elided. C++17 allows, but not requires, the copy to be elided even if the object has observable side effects in its copy/move constructors (and its destructor).

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148