哪个 C++对象复制速度更快?
该 C++ 对象存在两个实例。
my_type
{
public:
std::vector<unsigned short> a;
}
一种是 std::vector 为空,另一种是包含 50 个元素。
哪个实例复制速度最快还是同时复制?
Two instances of this C++ object exist.
my_type
{
public:
std::vector<unsigned short> a;
}
One where the std::vector is empty and the other where it contains 50 elements.
Which instance copies most quickly or do they copy in the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当复制
std::vector
时,它的所有元素也会被复制 - 因此所花费的时间应该与vector.size()
成正比。在
c++0x
中引入了所谓的move语义,允许为类型定义移动构造函数和移动赋值运算符。这些是为标准库容器(例如std::vector
)定义的,并且应该允许向量在O(1)
时间内移动。如果您担心性能,也许您可以重新调整操作以利用这些新功能。编辑:根据链接的问题,如果您担心调用
vector::push_back
时可能完成的额外副本,您有几个选择:c++0x
中请改用新的vector::emplace_back
。这允许您的对象在容器中就地构建。c++0x
中,通过vector.push_back(std::move(object_to_push))
等方式使用 move 语义。对于 POD 类型,这仍然会比emplace_back
选项执行更多的复制操作。希望这有帮助。
When a
std::vector
is copied all of it's elements are also copied - so the time taken should be proportional tovector.size()
.In
c++0x
so called move semantics are introduced, allowing a move constructor and move assignment operator to be defined for types. These are defined for standard library containers (such asstd::vector
) and should allow for vector's to be moved inO(1)
time. If you're worried about performance, maybe you could re-cast your operations to make use of these new features.EDIT: Based on the linked question, if you're worried about the extra copies potentially done when calling
vector::push_back
you have a few options:c++0x
use the newvector::emplace_back
instead. This allows for your objects to be constructed in-place in the container.c++0x
use move semantics, via something likevector.push_back(std::move(object_to_push))
. For POD types this will still do more copying than theemplace_back
option.Hope this helps.