哪个 C++对象复制速度更快?

发布于 2024-12-04 21:14:00 字数 185 浏览 0 评论 0原文

该 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

护你周全 2024-12-11 21:14:00

当复制 std::vector 时,它的所有元素也会被复制 - 因此所花费的时间应该与 vector.size() 成正比。

c++0x中引入了所谓的move语义,允许为类型定义移动构造函数和移动赋值运算符。这些是为标准库容器(例如std::vector)定义的,并且应该允许向量在O(1)时间内移动。如果您担心性能,也许您可​​以重新调整操作以利用这些新功能。

编辑:根据链接的问题,如果您担心调用 vector::push_back 时可能完成的额外副本,您有几个选择:

  1. c++0x 中请改用新的 vector::emplace_back。这允许您的对象在容器中就地构建。
  2. c++0x 中,通过 vector.push_back(std::move(object_to_push)) 等方式使用 move 语义。对于 POD 类型,这仍然会比 emplace_back 选项执行更多的复制操作。
  3. 存储指向对象而不是对象本身的指针的容器。在这种情况下,容器唯一会复制的是指针本身 - 这很便宜。您可能希望通过此选项使用智能指针的某些变体。

希望这有帮助。

When a std::vector is copied all of it's elements are also copied - so the time taken should be proportional to vector.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 as std::vector) and should allow for vector's to be moved in O(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:

  1. In c++0x use the new vector::emplace_back instead. This allows for your objects to be constructed in-place in the container.
  2. In c++0x use move semantics, via something like vector.push_back(std::move(object_to_push)). For POD types this will still do more copying than the emplace_back option.
  3. Store a container of pointers to objects rather than objects themselves. The only thing that will get copied by the container in this case is the pointer itself - which is cheap. You potentially want to use some variant of smart pointers with this option.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文