C++ 声明 const 变量,但推迟其初始化?

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

上下文:

一个函数(来自某些我无法修改的 API)returns 对来自 objectRegistry 的对象的常量引用:

const Foo& f(args)

我需要获取常量 Foo 对象,但我需要基于某些条件的 Foo 的不同实例。

天真,我先声明什么freturns,然后调用f初始化变量foo

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

这将不起作用,因为这将首先(我假设)调用一个带有空参数的构造函数。之后,您将拥有一个无法覆盖的 const 对象。相反,编译器会立即抱怨:error: 'foo' declared as reference but not initialized。如果将 foo 声明为 const Foo foo;

,也会出现同样的问题

以下确实有效。

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

问题:

有点相关的话题:

您可以使用包装器

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);
}

然后简单地

const Foo& foo = getFooWrapper();