【问题标题】:When should I declare a move constructor without noexcept?我什么时候应该声明一个没有 noexcept 的移动构造函数?
【发布时间】:2014-11-14 02:50:23
【问题描述】:

该标准不对移动构造函数强制执行 noexcept。在什么情况下可以接受/有必要抛出移动构造函数?

【问题讨论】:

  • +1,但请记住,移动是一种优化。在我看来,r 值引用是人们花费太多时间思考的事情之一。您可以编写的最佳移动构造函数是无。投掷移动构造函数不是一个好选择,但如果它是您唯一的选择,并且您的分析表明它是对关键路径上的复制的改进,那么很难反对它。

标签: c++ c++11 rvalue-reference


【解决方案1】:

当你真的别无选择时。大多数时候你的移动构造函数应该是noexcept。它们是默认的。

看到这个:http://www.codingstandard.com/rule/12-5-4-declare-noexcept-the-move-constructor-and-move-assignment-operator/

对以下类型使用 noexcept 尤为重要 旨在与标准库容器一起使用。如果搬家 容器中元素类型的构造函数不是 noexcept 然后 容器将使用复制构造函数而不是移动 构造函数。

【讨论】:

  • 你能举一个我别无选择时的例子吗?
  • @Klaufir 我猜如果你有(比方说)一个保证类原子行为的容器(它要么全部移动要么不移动任何东西)并且你的元素将不可复制(比如句柄)——所以没有 B 计划——那么你的元素类型就行不通了。
  • @Klaufir 不抱歉,我没有例子:(。也许更有经验的人可以想出一些办法。
【解决方案2】:

这里的黄金法则是:视情况而定

这是一个可能有意义的例子:

// A lock_guard template somewhere up here...

template<typename mutex_t>
class shared_lock_guard
{
    mutex_t *mtx_ptr;

public:

    shared_lock_guard(lock_guard<mutex_t> &&other) :
    mtx_ptr{other.mtx_ptr}
    {
        if(this->mtx_ptr){

            // this might throw a system_error
            // if the syscall fails or if the
            // lock state was corrupted.
            //
            this->mtx_ptr->shared_relock();
        }

        other.mtx_ptr = nullptr;
    }

    // rest of implementation, etc...
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-05
    • 2020-12-22
    • 2014-12-01
    • 2020-05-08
    • 2021-05-28
    • 2014-01-03
    • 2018-07-03
    • 1970-01-01
    相关资源
    最近更新 更多