C ++声明const变量,但是推迟了它的初始化?

时间:2017-08-15 13:31:10

标签: c++ initialization const-reference

上下文

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

const Foo& f(args)

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

Naievely,我首先声明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)之外,这个方法有什么问题吗?
  • 有没有更好的方法来达到同样目的?

有些相关主题

1 个答案:

答案 0 :(得分:2)

您可以使用包装器

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