vendredi 24 avril 2015

How to make default constructor defined outside the class noexcept?

I know that a constructor marked as =default will "try" to be noexcept whenever possible. However, if I define it outside the class, it is not noexcept anymore, as you can see from this code:

#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;
}

How can I define such a =default constructor outside a class and make it noexcept? And why is such a constructor noexcept(false) if defined outside the class? This issue arises when implementing PIMPL via smart pointers.

Aucun commentaire:

Enregistrer un commentaire