容器使用复制来填充调整大小

容器使用复制来填充调整大小

本文介绍了为什么 STL 容器使用复制来填充调整大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有实现 resize 的 STL 容器都使用副本来填充新元素,即使副本的源是默认构造对象?

all the STL containers that implement resize use copies to populate the new elements even if the source of the copy is a default constructed object?

为什么要这样做?

我看不到任何优势和一些成本.

I see no advantage and some cost.

作为上下文,我在寻找 不可复制元素的随机访问容器:

As context, I ran across this while looking for a random access container for elements that can't be copied:

推荐答案

它节省了复杂性.我们当然需要复制构造的情况,并且可以将默认构造建模为复制默认构造的对象.

It saves on complexity. We certainly need the copy-construction case, and default-construction can be modeled as replicating a default-constructed object.

性能损失可以忽略不计.写入零的速度与复制零的速度大致相同.兼容性损失为零,因为无论如何所有容器都需要可复制性.另一方面,不需要默认构造.

The performance penalty is negligible. Writing zeroes is about the same speed as copying zeroes. The compatibility penalty is nil since all containers require copyability anyway. Default-construction on the other hand isn't required.

如果您真的想将标准容器与不可复制的对象一起使用,请查看 C++0x 和使用 emplace 的就地构造.但是,没有方法可以一次emplace 多个元素.(如果您使用 dequeemplace 循环与 resize 相比应该不会有太大的性能损失.)

If you really want to use standard containers with non-copyable objects, look into C++0x and in-place construction with emplace. However, there is no method to emplace multiple elements at once. (If you're using deque, there shouldn't be much performance penalty to an emplace loop vs. resize though.)

这篇关于为什么 STL 容器使用复制来填充调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:52