C++ 声明常量变量,但推迟其初始化?
C++ Declare const variable, but postpone its initialisation?
>上下文:
一个函数(来自某些我无法修改的 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();
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- C++ 声明常量变量,但推迟其初始化?
- 是否可以在不修改父类的情况下将成员变量初始化推迟到继承的类?
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- 默认构造函数-推迟成员变量的初始化