Inserting an object having a non copyable field into an std::vector

我与影子孤独终老i 提交于 2019-12-13 00:24:25

问题


I understand that the following code does not compile since the move constructor of A is deleted because the mutex is not movable.

class A {
  public:
    A(int i) {}

  private:
    std::mutex m;

};


int main() {    
    std::vector<A> v;
    v.emplace_back(2);
}

But if I want my A to be stored in an std container how should I go about this? I am fine with A being constructed "inside" the container.


回答1:


std::vector::emplace_back may need to grow a vector's capacity. Since all elements of a vector are contiguous, this means moving all existing elements to the new allocated storage. So the code implementing emplace_back needs to call the move constructor in general (even though for your case with an empty vector it would call it zero times).

You wouldn't get this error if you used, say, std::list<A>.



来源:https://stackoverflow.com/questions/40049854/inserting-an-object-having-a-non-copyable-field-into-an-stdvector

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