First, the int variable is a C ++ object. Presumably, when you talk about C ++ objects, not int , you mean class type objects. But not just class type objects, because you can do this:
struct Blah{ int x; int y; }; auto main() -> int { Blah o;
So you probably mean an object of type class with at least one user-defined constructor.
The most common ways to delay the initialization of such an object with respect to declaring something used to access it include
std::vector as an expanding array,- direct dynamic distribution (regardless of how life time is managed) and
- code refactoring
& Hellip; where refactoring, in essence, is to move the subsequent usage code into a function or functions.
For example, ugly and ineffective deferred initialization code
unique_ptr<MyClass> p; if( condition() ) { // Some code here, then p.reset( new MyDerivedA( 123 ) ); } else { // Some code here, then p.reset( new MyDerivedB( "andromeda" ) ); } // Code using *p here.
& hellip; can be changed as
void foo( MyClass&& o ) { // Code using o here. } … if( condition() ) { // Some code here, then foo( MyDerivedA( 123 ) ); } else { // Some code here, then foo( MyDerivedB( "andromeda" ) ); }
Less common methods include
put new in some appropriately aligned byte array, as in your code, and
if your class is movable, use the Optional_ class (Barton-Nackman Fallible , Boost, and C ++ 17 optional ), which supports move assignment.
Whether these methods can be considered idiomatic in order to delay initialization, I think this is a very subjective personal opinion.
source share