Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initialization for stack objects?

I know we can do the following with heap objects:

/* Heap objects */
Pet *pet;

if (...)
    pet = new Pet("Dog");
else
    pet = new Pet("Cat");    

But how do we do it if we wanted the Pet object to be declared on the stack?

/* Stack objects */
Pet pet;

if (...)
    -?-
else
    -?-
like image 501
Ori Popowski Avatar asked Jan 23 '26 06:01

Ori Popowski


1 Answers

Try the following

Pet pet(theCondition ? "Dog" : "Cat");

Or if the conditional blocks are more complex than a single initialization store the const char* which is used for initialization as a separate local

const char* pArgument;
if (...) {
  ...
  pArgument = "Dog";
} else {
  ...
  pArgument = "Cat";
}

Pet pet(pArgument);
like image 90
JaredPar Avatar answered Jan 25 '26 18:01

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!