相关疑难解决方法(0)

是一个`= default`移动构造函数,等同于成员移动构造函数吗?

这是

struct Example { 
    int a, b; 
    Example(int mA, int mB) : a{mA}, b{mB}               { }
    Example(const Example& mE) : a{mE.a}, b{mE.b}        { }
    Example(Example&& mE) : a{move(mE.a)}, b{move(mE.b)} { }
    Example& operator=(const Example& mE) { a = mE.a; b = mE.b; return *this; } 
    Example& operator=(Example&& mE)      { a = move(mE.a); b = move(mE.b); return *this; } 
}
Run Code Online (Sandbox Code Playgroud)

相当于此

struct Example { 
    int a, b; 
    Example(int mA, int mB) : a{mA}, b{mB} { }
    Example(const Example& mE)            = default; …
Run Code Online (Sandbox Code Playgroud)

c++ constructor default move-semantics c++11

90
推荐指数
3
解决办法
3万
查看次数

为什么我默认的移动构造函数不是 noexcept?

根据this question的答案,可以noexcept在某些条件下定义默认移动构造函数。例如,下面的类生成一个noexcept移动构造函数:

class C {};
Run Code Online (Sandbox Code Playgroud)

根据对这个问题的回答,使用说明= default符定义的移动构造函数将生成与隐式定义的移动构造函数相同的构造函数。所以,如果我正确理解它,下面的类应该生成一个noexcept移动构造函数:

class D {
    D(D&&) = default;
};
Run Code Online (Sandbox Code Playgroud)

要检查,我使用的std::is_nothrow_move_constructible功能,看是否CD有一个noexcept移动构造函数:

#include <type_traits>

int main() {
    static_assert(std::is_nothrow_move_constructible<C>::value, "C should be noexcept MoveConstructible");
    static_assert(std::is_nothrow_move_constructible<D>::value, "D should be noexcept MoveConstructible");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我编译时,我收到此错误:

$ g++ toy.cpp -o toy
toy.cpp: In function ‘int main()’:
toy.cpp:16:5: error: static assertion failed: D should be noexcept MoveConstructible
     static_assert(std::is_nothrow_move_constructible<D>::value, "D should be …
Run Code Online (Sandbox Code Playgroud)

c++ move-constructor noexcept c++11

28
推荐指数
2
解决办法
1048
查看次数