移出某些元素后无法从矢量中删除

Can't erase from vector after having moved out some elements

本文关键字:删除 元素 移出      更新时间:2023-10-16

您好,我正在尝试了解如何优化将元素从一个向量移动到另一个向量,检查是否正在调用复制或移动构造函数。

但是,当我尝试从移动到另一个向量v2std::vectorv1中删除元素时,编译器会抱怨以下消息:

vector-move-elements.cpp:19:5: note: copy assignment operator is implicitly deleted because 'Foo' has a
user-declared move constructor
Foo(Foo&& other) {
^

这是代码

#include <vector>
#include <string>
#include <iostream>
// #include <algorithm> std::copy_if
// inspired from https://stackoverflow.com/questions/15004517/moving-elements-from-stdvector-to-another-one
struct Foo
{
Foo(std::string&& s, uint32_t idx) {
this->name = std::move(s);
this->index = std::move(idx);
std::cout << "Calling default constructor " << name << idx << std::endl;
}
Foo(const Foo& other) {
this->name = other.name;
this->index = other.index;
std::cout << "Calling copy constructor " << other.name << other.index << std::endl;
}
Foo(Foo&& other) {
this->name = std::move(other.name);
this->index = std::move(other.index);
std::cout << "Calling move constructor " << other.name << other.index << std::endl;
}
std::string name;
uint32_t index;
};
int main() {
std::vector<Foo> v1, v2;
v1.reserve(25); // https://stackoverflow.com/questions/52109542/push-back-to-stdvector-the-copy-constructor-is-repeatedly-called
v2.reserve(25); // without this the push_back instruction causes a call to copy constructor
// fill v1 with dummy elements
for (uint32_t i = 0; i < 25; ++i ) {
std::string s = std::string("name_") + std::to_string(i);
std::cout << s << std::endl;
v1.emplace_back(Foo(std::move(s), i));
}
std::cout << "End of construction" << std::endl;
// populate v1 with at least 17 elements...
const auto it = std::next(v1.begin(), 17); // same as v1.begin()+17;
std::move(v1.begin(), it, std::back_inserter(v2));
// std::copy_if(std::make_move_iterator(begin(v1)),
//          std::make_move_iterator(end(v1)),
//          std::back_inserter(v2),
//          [](const Foo& v){ return v.index <= 17; });
// this line DOESN'T COMPILE 
v1.erase(v1.begin(), it); // copy assignment operator is implicitly deleted because 'Foo' has a
user-declared move constructor
// if I don't loop on auto& the for loop will call copy constructor
for (auto const& e : v1) {
std::cout << "v1: " << e.name << " " << e.index << std::endl;
}
for (auto const& e : v2) {
std::cout << "v2: " << e.name << " " << e.index << std::endl;
}
}

您需要检查的是三/五/零的规则。

您需要一个复制赋值运算符来编译代码:

Foo& operator=(const Foo& other) {
this->name = other.name;
this->index = other.index;
std::cout << "Calling copy assignment " << other.name << other.index << std::endl;
return *this;
}

以及要遵守 5 规则的移动分配运算符。

活在神霹雳上