Search code examples
c++initializationconst-reference

C++ Declare const variable, but postpone its initialisation?


Context:

A function (from some API I cannot modify) returns a constant reference to an object from an objectRegistry:

const Foo& f(args)

I need to obtain the constant Foo object, but I require a different instance of Foo based on some conditional.

Naievely, I'd first declare what f returns, and then call f to initialise the variable foo.

const Foo& foo; // Declare
if( something == true ){
    foo = f(arg1); // Initialise
}else{
    foo = f(arg2); // Initialise
}
// It is guaranteedly initialised in this line

This will not work, as this will first (I assume) call a constructor with empty argument. Afterwards you have a const object that you cannot overwrite. Rather, the compiler immediately complains: error: 'foo' declared as reference but not initialized. The same problem occurs if foo is declared as const Foo foo;

The following does work.

const Foo* fooPtr;
if( something == true ){
    fooPtr = &f(1);
}else{
    fooPtr = &f(2);
}
const Foo& foo = *fooPtr;

Questions:

  • Are there any issues with this method, other than being ugly (imo)?
  • Are there nicer ways to the same end?

Somewhat related topics:


Solution

  • You could use a wrapper

    const Foo& getFooWrapper(something) {  // assume returning a ref is fine,                                         
        if (something) return f(1);        // because f already returns a const&
        else           return f(2);
    }
    

    and then simply

    const Foo& foo = getFooWrapper();