#Best way to run lazy global initialization code only once

7 messages · Page 1 of 1 (latest)

hard raptor
#

So I have a function like this that does lazy initialization:

Wrapper& getWrapper() {
  // initialization code
  
  return gWrapper;
}

But the initialization code isn't trivial and I want to only run it that once im actually constructing the gWrapper. Other times, it should just return gWrapper immediately. How can I best do this?

spark ferryBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

knotty grail
fervent salmon
#

Or if you don't want to do that in Wrapper's constructor for some reason, you can use an immediately invoked lambda:

Wrapper &getWrapper()
{
    static Wrapper ret = []{
        Wrapper w;
        // do something to `w`
        return w;
    }();
    return ret;
}
hard raptor
#

!solved