我一直以为std::initializer_list
是一个轻量级代理对象,它只会从列表项中获取 const 引用,而不是复制它们。
但后来我发现在这种情况下实际上执行了复制:
struct Test {
Test() {
std::cout << this << " default ctor" << std::endl;
}
Test(const Test&) {
std::cout << this << " copy ctor" << std::endl;
}
~Test() {
std::cout << this << " destructor" << std::endl;
}
};
int main() {
Test a;
Test b;
Test c;
std::cout << "for begin" << std::endl;
for(const auto& current : {a, b, c}) {
std::cout << "Current: " << ¤t << std::endl;
}
std::cout << "for end" << std::endl;
}
上述代码的输出:
0x63e5acda default ctor
0x63e5acdb default ctor
0x63e5acdc default ctor
for begin
0x63e5acdd copy ctor
0x63e5acde copy ctor
0x63e5acdf copy ctor
Current: 0x63e5acdd
Current: 0x63e5acde
Current: 0x63e5acdf
0x63e5acdf destructor
0x63e5acde destructor
0x63e5acdd destructor
for end
0x63e5acdc destructor
0x63e5acdb destructor
0x63e5acda destructor
在这种情况下,为什么 std::initializer_list 会复制项目,而不是仅仅获取它们的引用?有没有什么“优雅”的方式来写类似的东西for(auto&& x : {a, b, c})
,但不复制现有项目?
从文档上std::initializer_list https://en.cppreference.com/w/cpp/utility/initializer_list:
底层数组是一个 const T[N] 类型的临时数组,其中每个元素都是复制初始化的(除非缩小转换无效)来自原始初始值设定项列表的相应元素。底层数组的生命周期与任何其他临时对象相同,除了从数组初始化一个initializer_list对象会延长数组的生命周期,就像将引用绑定到临时对象一样(有相同的例外,例如初始化一个非-静态类成员)。底层数组可以分配在只读存储器中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)