上下文:
一个函数(来自某些我无法修改的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;
问题:
有些相关主题:
答案 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();