可以在C 17中汇总初始化
Can copy elision be perfomed in aggregate initialization in c++17?
本文关键字:初始化 更新时间:2023-10-16
给定:
//C++17
#include <string>
struct Foo {
int i;
std::string str;
};
int main() {
Foo foo{1, std::string("Hello, world!")};
}
Foo::i
和Foo::str
可以直接从1
和std::string(...)
初始初始化,而不是被复制到它们中,并解释为什么/不能/不能使用C 17标准(可能是用于测试目的的某些代码)?
如果不能,需要多少份?
汇总初始化基本上执行元素副本限制。因此:
struct Foo {
int i;
std::string str;
};
Foo foo{1, std::string("Hello, world!")};
执行与:
的初始化相同的初始化int i = 1;
std::string str = std::string("Hello, world!");
,我们在C 17中有一个新规则,该规则说:
如果初始化器表达式是prvalue,并且源类型的CV UNCOLIFIED版本与目标类别相同,则使用初始化器表达式来初始化目标对象。 [示例:
T x = T(T(T()));
调用T
默认构造函数以初始化x
。 - 结束示例]
这意味着第二个初始化必须表现得像您写的那样:
std::string str("Hello, world!");
即,零副本。
新规则的一个很好的证明是以下示例:
struct X {
X(int ) { }
X(X&& ) = delete;
};
struct Y {
X x;
};
int main() {
Y y{X{4}}; // ill-formed in C++14 due to deleted move ctor
// ok in C++17, no move required
}
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 在函数内部的声明中初始化数组,并在外部使用它
- 继承:构造函数,初始化C++11中基类的类C数组成员