如何调用移动构造函数的矢量复制构造函数?



查看cppreference,我看到:

vector( const vector& other, const Allocator& alloc ); // copy constructor
vector( vector&& other ); // move constructor

我想从另一个向量的实例中形成一个向量(尽可能有效地窃取其内容),这是这样做的吗:

vector<double>my_vec(std::move(my_other_vec)); // move construction
my_vec = std::move(my_other_vec); // move assignment

,如果是,为了在副本上调用move构造函数,是否总是需要将函数调用传递给std::move?

那么我是否可以使用my_other_vec作为空向量来做事情?

您可以通过直接调用remove reference来调用move构造函数。例如

#include <vector>
#include <iostream>
template<class I>
void print_all(I begin, I end)
{
std::cout << '[';
if(begin != end) {
std::cout << *begin;
while(++begin != end) {
std::cout << ',' << *begin;
}
}
std::cout << ']' << std::endl;
}
int main(int argc, const char** argv) 
{    
std::vector<int> src  {{0,1,2,3,4,5,6,7}};
std::cout << "Before movement: ";
print_all(src.begin(), src.end());
std::vector<int> dst( std::move(src) );
std::cout << "After movement: ";
print_all(src.begin(), src.end());
std::cout << "Moved: ";
print_all(dst.begin(), dst.end());
return 0;
}

它将返回你:

Before movement: [0,1,2,3,4,5,6,7]
After movement: []
Moved: [0,1,2,3,4,5,6,7] 

可以看到,vector的数据从一个实例移动到另一个实例。您可以使用vector::swap来获得相同的行为。

最新更新