一系列临时工可能吗?

问题描述 投票:1回答:2

移动支持以窃取临时对象的内部以避免复制。是否可以创建临时对象的原始数组?即vector不属于这一类。

struct Employee{};

Employee{}; // this creates temporary
Employee [10]; // compiler error, expected identifier before numeric constant
c++
2个回答
1
投票

是的,可以有物化阵列prvalues。您需要使用类型别名,因为案例T{}的类型说明符必须是单个标识符:

using array_t = Employee[10];
array_t{};

prvalue也可以进行数组到指针的转换,例如:

void func(Employee const* ptr);
// ...
func( array_t{} );

0
投票

延长临时生命周期的唯一好方法是获取并保持对它的引用。

这样的事可能有用

using Ecref = const Employee&;

Ecref a[10] = {Employee("John"), Employee("Mary"), ...};

但是,不幸的是,C ++中禁止引用数组(const和非const)。

© www.soinside.com 2019 - 2024. All rights reserved.