在C++ 11中实现复制和交换习惯用法的更好方法

Che*_*han 11 c++ c++11

我看到许多代码在复制和交换方面实现了五个规则,但我认为我们可以使用移动函数来替换交换函数,如下面的代码所示:

#include <algorithm>
#include <cstddef>

class DumbArray {
public:
    DumbArray(std::size_t size = 0)
        : size_(size), array_(size_ ? new int[size_]() : nullptr) {
    }

    DumbArray(const DumbArray& that)
        : size_(that.size_), array_(size_ ? new int[size_] : nullptr) {
        std::copy(that.array_, that.array_ + size_, array_);
    }

    DumbArray(DumbArray&& that) : DumbArray() {
        move_to_this(that);
    }

    ~DumbArray() {
        delete [] array_;
    }

    DumbArray& operator=(DumbArray that) {
        move_to_this(that);
        return *this;
    }

private:
    void move_to_this(DumbArray &that) {
        delete [] array_;
        array_ = that.array_;
        size_ = that.size_;
        that.array_ = nullptr;
        that.size_ = 0;
   }

private:
    std::size_t size_;
    int* array_;
};
Run Code Online (Sandbox Code Playgroud)

我想这个代码

  1. 例外安全
  2. 需要更少的输入,因为许多函数只调用move_to_this(),并且复制赋值和移动赋值在一个函数中统一
  3. 比复制和交换更有效,因为交换涉及3个分配,而这里只有2个,并且此代码不会遇到此链接中提到的问题

我对吗?

谢谢

编辑:

  1. 正如@Leon指出的那样,可能需要一个用于释放资源的专用函数,以避免代码重复move_to_this()和析构函数
  2. 作为@thorsan指出,极端的性能问题,最好是单独DumbArray& operator=(DumbArray that) { move_to_this(that); return *this; }DumbArray& operator=(const DumbArray &that) { DumbArray temp(that); move_to_this(temp); return *this; }(感谢@MikeMB),并DumbArray& operator=(DumbArray &&that) { move_to_this(that); return *this; }避免额外的举动operatoin

    添加一些调试打印后,我发现DumbArray& operator=(DumbArray that) {}当您将其称为移动分配时不会涉及额外的移动

  3. 正如@ErikAlapää指出的那样,在delete进入之前需要进行自我分配检查move_to_this()

Ric*_*ges 8

评论内联,但简要说明:

  • 你想要所有的移动任务和移动构造函数,noexcept如果可能的话.标准库是多少,如果你启用这个功能,因为它的Elid可以任何异常从中重新排列对象的序列算法,处理速度更快.

  • 如果您要定义自定义析构函数,请将其设置为noexcept.为什么打开潘多拉的盒子?我错了.默认情况下,这是noexcept.

  • 在这种情况下,提供强大的异常保证是无痛的,几乎没有任何成本,所以让我们这样做.

码:

#include <algorithm>
#include <cstddef>

class DumbArray {
public:
    DumbArray(std::size_t size = 0)
    : size_(size), array_(size_ ? new int[size_]() : nullptr) {
    }

    DumbArray(const DumbArray& that)
    : size_(that.size_), array_(size_ ? new int[size_] : nullptr) {
        std::copy(that.array_, that.array_ + size_, array_);
    }

    // the move constructor becomes the heart of all move operations.
    // note that it is noexcept - this means our object will behave well
    // when contained by a std:: container
    DumbArray(DumbArray&& that) noexcept
    : size_(that.size_)
    , array_(that.array_)
    {
        that.size_ = 0;
        that.array_ = nullptr;
    }

    // noexcept, otherwise all kinds of nasty things can happen
    ~DumbArray() // noexcept - this is implied.
    {
        delete [] array_;
    }

    // I see that you were doing by re-using the assignment operator
    // for copy-assignment and move-assignment but unfortunately
    // that was preventing us from making the move-assignment operator
    // noexcept (see later)
    DumbArray& operator=(const DumbArray& that)
    {
        // copy-swap idiom provides strong exception guarantee for no cost
        DumbArray(that).swap(*this);
        return *this;
    }

    // move-assignment is now noexcept (because move-constructor is noexcept
    // and swap is noexcept) This makes vector manipulations of DumbArray
    // many orders of magnitude faster than they would otherwise be
    // (e.g. insert, partition, sort, etc)
    DumbArray& operator=(DumbArray&& that) noexcept {
        DumbArray(std::move(that)).swap(*this);
        return *this;
    }


    // provide a noexcept swap. It's the heart of all move and copy ops
    // and again, providing it helps std containers and algorithms 
    // to be efficient. Standard idioms exist because they work.
    void swap(DumbArray& that) noexcept {
        std::swap(size_, that.size_);
        std::swap(array_, that.array_);
    }

private:
    std::size_t size_;
    int* array_;
};
Run Code Online (Sandbox Code Playgroud)

在移动赋值运算符中可以进一步提高性能.

我提供的解决方案提供了一个保证,即移动的数组将为空(资源被释放).这可能不是你想要的.例如,如果您单独跟踪DumbArray的容量和大小(例如,像std :: vector),那么您可能希望在移动后this保留任何已分配的内存that.然后,这将允许that被分配,同时可能在没有另一个存储器分配的情况下离开.

为了实现这种优化,我们只需根据(noexcept)swap实现move-assign运算符:

所以从这个:

    /// @pre that must be in a valid state
    /// @post that is guaranteed to be empty() and not allocated()
    ///
    DumbArray& operator=(DumbArray&& that) noexcept {
        DumbArray(std::move(that)).swap(*this);
        return *this;
    }
Run Code Online (Sandbox Code Playgroud)

对此:

    /// @pre that must be in a valid state
    /// @post that will be in an undefined but valid state
    DumbArray& operator=(DumbArray&& that) noexcept {
        swap(that);
        return *this;
    }
Run Code Online (Sandbox Code Playgroud)

在DumbArray的情况下,在实践中使用更放松的形式可能是值得的,但要注意微妙的错误.

例如

DumbArray x = { .... };
do_something(std::move(x));

// here: we will get a segfault if we implement the fully destructive
// variant. The optimised variant *may* not crash, it may just do
// something_else with some previously-used data.
// depending on your application, this may be a security risk 

something_else(x);   
Run Code Online (Sandbox Code Playgroud)

  • 现在默认情况下不是析构函数`noexcept(true)`吗? (2认同)

Leo*_*eon 1

代码中唯一的(小)问题是析构函数之间的功能重复move_to_this(),如果您的类需要更改,这是一个维护问题。当然可以通过将该部分提取到一个公共函数中来解决destroy()

我对斯科特·迈耶斯在他的博客文章中讨论的“问题”的批评:

他尝试手动优化编译器在足够智能的情况下可以做得同样好的工作。五规则可以简化为四规则:

  • 仅提供按值获取其参数的复制赋值运算符
  • 不费心去写移动赋值运算符(正是你所做的)。

这自动解决了如果右侧对象不是临时对象,则左侧对象的资源被交换到右侧对象而没有立即释放的问题。

然后,在根据复制和交换习惯用法的复制赋值运算符的实现中,swap()将把过期对象作为其参数之一。delete如果编译器可以内联后者的析构函数,那么它肯定会消除额外的指针赋值 - 事实上,为什么要保存下一步将要编辑的指针呢?

我的结论是,遵循成熟的习惯用法更简单,而不是为了成熟编译器完全可以实现的微优化而使实现稍微复杂化。