c++ - initializer_list 不可变的性质导致过度复制

标签 c++ c++11 move-semantics c++14 initializer-list

为什么访问 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/

相关文章:

c++ - 函数返回值和右值引用绑定(bind)

c++ - 在特定网络接口(interface) Linux/Unix 上使用 C++ TCP 客户端套接字

c++ - 如何检查 map::lower_bound 失败?

c++ - 你知道在 C++ 中获取线程本地存储的不同方法的一些性能测试吗?

c++ - OpenCV:如何对带有图像的文件夹进行批处理?

c++ - "Defaulted" move 构造函数和赋值 - 奇怪的行为

c++ - 我如何对没有复制构造函数的对象使用 std::sort?

c++ - 如何查找数组中的重复项数?

C++ 无效转换

c++ - VS2015错误C2976