什么时候应该声明一个没有noexcept的移动构造函数?

时间:2014-11-14 02:50:24

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

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

2 个答案:

答案 0 :(得分:5)

当你真的别无选择。大多数情况下,移动构造函数应为noexcept。它们是默认的。

请参阅:http://www.codingstandard.com/rule/12-5-4-declare-noexcept-the-move-constructor-and-move-assignment-operator/

  

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

答案 1 :(得分:4)

这里的黄金法则是:取决于

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

// 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...
};