Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 549
vsoftco Avatar asked Apr 24 '15 15:04

vsoftco


People also ask

Are default constructors Noexcept?

Inheriting constructors and the implicitly-declared default constructors, copy constructors, move constructors, destructors, copy-assignment operators, move-assignment operators are all noexcept(true) by default, unless they are required to call a function that is noexcept(false) , in which case these functions are ...

What does Noexcept mean in C++?

noexcept (C++) C++11: Specifies whether a function might throw exceptions.

Is default constructor is not defined then how the objects of the class will be created?

Default constructor must be defined, if parameterized constructor is defined and the object is to be created without arguments. Explanation: If the object is create without arguments and only parameterized constructors are used, compiler will give an error as there is no default constructor defined.

How is a default constructor defined?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


1 Answers

I realized now that I can do this, it didn't cross my mind until now:

struct Foo
{
    Foo() = default;
    Foo(Foo&&) noexcept;
};
Foo::Foo(Foo&&) noexcept = default; // now it is noexcept

Still the second question Why is it noexcept(false) by default? applies.

like image 72
vsoftco Avatar answered Oct 21 '22 15:10

vsoftco