initializer_list不变的性质会导致过度复制 [英] initializer_list immutable nature leads to excessive copying
问题描述
为什么对std::initializer_list
的访问不允许我们更改其内容? std::initializer_list
主要用途(初始化容器)时,这是一个很大的缺点,因为std::initializer_list
的使用会导致过多的复制构造/复制分配,而不是移动构造/移动分配.
Why does the access to std::initializer_list
not allow us to change its content? It's a big disadvantage of std::initializer_list
when using it for its main purpose (to initialize a container), since it's use leads to excessive copy-construction/copy-assignment, instead of move-construction/move-assignment.
#include <initializer_list>
#include <iostream>
#include <vector>
#include <cstdlib>
struct A
{
A() = default;
A(A const &) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
A(A &&) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
A & operator = (A const &) { std::cout << __PRETTY_FUNCTION__ << std::endl; return *this; }
A & operator = (A &&) { std::cout << __PRETTY_FUNCTION__ << std::endl; return *this; }
};
int
main()
{
std::vector< A >{A{}, A{}, A{}};
return EXIT_SUCCESS;
}
输出(符合预期):
A::A(const A &)
A::A(const A &)
A::A(const A &)
为什么它的设计如此受限制?
Why is its design so constrained?
推荐答案
There is a recent proposal for movable initializer lists, where, in particular, the authors say:
std::initializer_list
大约在2005(N1890)至2007(N2215)之前设计, 移动语义在2009年左右成熟.当时,没有想到复制语义 对于常见的类似于价值的类,将是不够的,甚至不是最佳的.有一个2008 提案N2801 Initializer列出并移动了语义,但当时C ++ 0x感觉已经不合时宜了,到2011年,此案变得很冷淡.
std::initializer_list
was designed around 2005 (N1890) to 2007 (N2215), before move semantics matured, around 2009. At the time, it was not anticipated that copy semantics would be insufficient or even suboptimal for common value-like classes. There was a 2008 proposal N2801 Initializer lists and move semantics but C++0x was already felt to be slipping at that time, and by 2011 the case had gone cold.
这篇关于initializer_list不变的性质会导致过度复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!