上下文:
一个函数(来自一些我无法修改的 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)之外,这种方法有什么问题吗?
- 有更好的方法来达到同样的目的吗?
一些相关的主题: