预期在 std::vector 的元素上移动,但在尝试将其作为参数传递时遇到了复制
Expected move on std::vector's elements but copy encountered instead when trying to pass it as a parameter
为什么下面的代码调用了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});
}
输出如下:
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
我期望没有副本,因为向量是在适当的位置创建的,并作为右值引用传递,然后移动。到底发生了什么?
std::initializer_list<T>
是 const T
对象数组的包装器。 (更准确地说,std::initializer_list<T>::reference
是 const T&
)。注意 const
。它必须是那样的,因为它的元素可以是文字。
这意味着std::vector
的构造函数采用std::initializer_list
必须将列表中的元素复制到向量中,它不能移动它们。
为什么下面的代码调用了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});
}
输出如下:
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
我期望没有副本,因为向量是在适当的位置创建的,并作为右值引用传递,然后移动。到底发生了什么?
std::initializer_list<T>
是 const T
对象数组的包装器。 (更准确地说,std::initializer_list<T>::reference
是 const T&
)。注意 const
。它必须是那样的,因为它的元素可以是文字。
这意味着std::vector
的构造函数采用std::initializer_list
必须将列表中的元素复制到向量中,它不能移动它们。