我知道标记为 =default
的构造函数将尽可能“尝试”为 noexcept
。但是,如果我在类的外部 定义它,它就不再是noexcept
,您可以从这段代码中看到:
#include <iostream>
#include <utility>
#include <type_traits>
struct Bar
{
Bar() = default;
Bar(Bar&&) = default; // noexcept
};
struct Foo
{
Foo() = default;
Foo(Foo&&);
};
// moving the definition outside makes it noexcept(false)
Foo::Foo(Foo&&) = default; // not noexcept anymore
int main()
{
Foo foo;
Bar bar;
std::cout << std::boolalpha;
// checks
std::cout << std::is_nothrow_move_constructible<Bar>::value << std::endl;
std::cout << std::is_nothrow_move_constructible<Foo>::value << std::endl;
}
如何在类外部定义这样一个=default
构造函数并使其成为noexcept
?为什么这样的构造函数 noexcept(false)
如果定义在类之外呢?实现 PIMPL 时会出现此问题通过智能指针。
最佳答案
我现在意识到我可以做到这一点,直到现在我才想到:
struct Foo
{
Foo() = default;
Foo(Foo&&) noexcept;
};
Foo::Foo(Foo&&) noexcept = default; // now it is noexcept
还是第二个问题为什么noexcept(false)
默认?适用。
关于c++ - 如何在类 noexcept 之外定义默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29850923/