C++11 预期在std::vector'上移动;s元素,但在尝试将其作为参数传递时遇到复制
为什么下面的代码调用C++11 预期在std::vector'上移动;s元素,但在尝试将其作为参数传递时遇到复制,c++11,move-semantics,C++11,Move Semantics,为什么下面的代码调用a的复制构造函数 class a { public: a(int x) : x_(x) { std::cout << "a constructor" << std::endl; } a(a&& a_) { std::cout << "a move constructor" << std::endl; } a(const a& a_) { std::cout << "a
a
的复制构造函数
class a {
public:
a(int x) : x_(x) { std::cout << "a constructor" << std::endl; }
a(a&& a_) { std::cout << "a move constructor" << std::endl; }
a(const a& a_) { std::cout << "a copy constructor" << std::endl; }
private:
int x_;
};
class b {
public:
b(std::vector<a>&& v) : v_(std::move(v)) {}
private:
std::vector<a> v_;
};
int main() {
b s({2, 3, 4, 5, 6});
}
我不希望有副本,因为向量是就地创建的,并作为右值引用传递,然后移动。实际发生了什么?
std::initializer\u list
是一个围绕const T
对象数组的包装器。(更准确地说,是常量&
)。注意常量
。它必须是这样的,因为它的元素可以是文字
这意味着
std::vector
的构造函数采用std::initializer\u list
必须将列表中的元素复制到向量中,它无法移动它们。更准确地说,原因是构造函数采用std::initializer\u list
(其中T
是向量的值类型)并且没有模板化以获取std::initializer\u列表
(带有一些X
)。否则,向量可以构造a
s。
a constructor
a constructor
a constructor
a constructor
a constructor
a copy constructor
a copy constructor
a copy constructor
a copy constructor
a copy constructor