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

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

本文关键字:推迟 初始化 声明 常量 变量 C++      更新时间:2023-10-16

>上下文

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

const Foo& f(args)

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

天真地,我会首先声明 f 返回什么,然后调用 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;

问题

  • 除了丑陋(imo(之外,这种方法还有什么问题吗?
  • 有没有更好的方法来达到同样的目的?

一些相关的主题

  • 从函数返回对局部变量的常量引用
  • -

您可以使用包装器

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