简体   繁体   English

std :: vector如何复制其数据以进行重新分配?

[英]How does an std::vector copy its data for reallocation?

I wrote a template array class similar to std::vector except it reuses empty indices or 'holes' when an element is erased, instead of moving all the following elements back to fill it. 我写了一个类似于std :: vector的模板数组类,除了它在擦除一个元素时重用空索引或“空洞”,而不是将以下所有元素移回以填充它。

I ran into a bug though when I tried to store a nontrivial object as I was using memcpy to copy elements during reallocation. 但是,当我尝试在重新分配期间使用memcpy复制元素时,尝试存储一个非平凡的对象时遇到了一个错误。 Does std::vector loop through all its elements and call the copy constructor, or does it use some other trick that I'm unaware of? std :: vector是否遍历所有元素并调用复制构造函数,还是使用了我不知道的其他技巧?

Yes, copying the elements then destroying the originals is the basic idea. 是的,复制元素然后销毁原稿是基本想法。

You can optimize with template metaprogramming, of course: 您当然可以使用模板元编程进行优化:

  • If the type has a trivial copy constructor, you can use memcpy 如果类型具有简单的副本构造函数,则可以使用memcpy
  • If the type has a trivial destructor, you can skip that step 如果类型具有琐碎的析构函数,则可以跳过该步骤

C++11 adds a new dimension in that you can move the objects too. C ++ 11增加了新的维度,您也可以移动对象。

No, you should not use memcpy() for non-pods. 不,您不应该将memcpy()用于非豆荚。 Classic vanilla C++03 implementation would be to use copy constructor, but this is not very productive. 经典的香草C ++ 03实现将使用复制构造函数,但这并不是很有效。 In C++11, you can use whole arsenal of meta-info, such as is_trivially_copyable to perform memcpy() when applicable, check for presence of move constructor, etc. 在C ++ 11中,您可以使用整个meta-info库(例如is_trivially_copyable)在适用时执行memcpy(),检查move构造函数的存在等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM