为什么 SGI STL 不使用复制和交换习语? [英] Why SGI STL don't use the copy-and-swap idiom?

查看:26
本文介绍了为什么 SGI STL 不使用复制和交换习语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 StackOverflow 上阅读了关于 什么是复制和-的答案交换习语?并且知道复制和交换习语可以

I recently read an answer on StackOverflow about What is the copy-and-swap idiom? and knew that the copy-and-swap idiom can

避免代码重复,并提供强大的异常保证.

avoiding code duplication, and providing a strong exception guarantee.

然而,当我查看 SGI STL deque 实现,我发现它没有使用这个成语.我想知道为什么不,如果这个习语有点像最佳实践"?

However, when I looked into SGI STL deque implementation, I found that it doesn't use the idiom. I'm wondering why not, if the idiom is somehow like a "best practice"?

  deque& operator= (const deque& __x) {
    const size_type __len = size();
    if (&__x != this) {
      if (__len >= __x.size())
        erase(copy(__x.begin(), __x.end(), _M_start), _M_finish);
      else {
        const_iterator __mid = __x.begin() + difference_type(__len);
        copy(__x.begin(), __mid, _M_start);
        insert(_M_finish, __mid, __x.end());
      }
    }
    return *this;
  }       

推荐答案

除非容器需要增长,否则您展示的代码不会重新分配内存,这可以节省大量资金.复制和交换总是分配内存来进行复制,然后为现有元素释放内存.

The code you show doesn't reallocate memory unless the container needs to grow, which can be a significant saving. Copy-and-swap always allocates memory to do the copy then deallocates the memory for the existing elements.

考虑一个 deque>,其中双端队列的现有向量成员具有大容量.

Consider a deque<vector<int>> where the existing vector members of the deque have large capacities.

deque<vector<int>> d(2);
d[0].reserve(100);
d[1].reserve(100);

使用 SGI STL 实现,分配给每个元素会保留该容量,因此如果向量需要增长,他们可以在不分配任何内容的情况下这样做:

Using the SGI STL implementation, assigning to each element preserves that capacity, so if the vectors need to grow they can do so without allocating anything:

d = deque<vector<int>>(2);
assert(d[0].capacity() >= 100);
assert(d[1].capacity() >= 100);
d[0].push_back(42);  // does not cause an allocation

Copy-and-swap 会将现有成员替换为没有空闲容量的新元素,因此上述断言将失败,并且 push_back 将需要分配内存.这浪费了释放和重新分配的时间,而不是使用已经存在的完美内存.

Copy-and-swap would replace the existing members with new elements that have no spare capacity, so the assertions above would fail, and the push_back would need to allocate memory. This wastes time deallocating and reallocating, instead of using the perfectly good memory that's already there.

复制和交换是一种很容易获得异常安全性和正确性的便捷方法,但不一定尽可能有效.在像 STL 或 C++ 标准库这样的代码中,你不想为了稍微更容易实现而牺牲效率,并且这样的代码通常应该由能够通过艰难的方式"获得异常安全的专家编写" 不仅仅是最方便的方式.

Copy-and-swap is a convenient way to get exception-safety and correctness very easily, but not necessarily as efficiently as possible. In code like the STL or the C++ Standard Library you do not want to sacrifice efficiency for the sake of slightly easier implementation, and such code should usually be written by experts who are able to get exception-safety right by doing it "the hard way" not just the most convenient way.

这篇关于为什么 SGI STL 不使用复制和交换习语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆