std::vector::erase(item) needs assignment operator to be defined for item?

半世苍凉 提交于 2019-12-01 16:32:25

The reason is that erase will reallocate your objects if you erase a different position than std::vector::end(). A reallocation implicates copying.

Notice that a vector of an uncopyable type is only partially useable. Before we had emplace() (pre-C++11) it was even impossible. If your class is however copyable, why dont you define an assignment operator then?

A workaround could be a vector of smartpointers (or normal pointers) like std::vector<std::unique_ptr<C>>

That's correct. The standard requires that items in a vector or deque be MoveAssignable if erase is to work.

In general, vectors and deques need to be able to erase from arbitrary positions. When they do, they need to be able to shift any remaining items into the space vacated by the erased item. The standard says (or implies, anyway, by its MoveAssignable requirement on erase) that they do that by assigning, so the contained item needs an assignment operator. Another option could have been for the items to be copied as by the copy constructor, but that's not how it's done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!