为什么访问 std::initializer_list
不允许我们改变它的内容?在将 std::initializer_list
用于其主要目的(初始化容器)时,这是一个很大的缺点,因为它的使用会导致过多的复制构造/复制赋值,而不是 move 构造/move 分配。
#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;
}
Output (如预期的那样):
A::A(const A &)
A::A(const A &)
A::A(const A &)
为什么它的设计如此受限?
最佳答案
最近有一个proposal for movable initializer lists ,特别是作者说:
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.
关于c++ - initializer_list 不可变的性质导致过度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194519/