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.
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 ...
noexcept (C++) C++11: Specifies whether a function might throw exceptions.
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.
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() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With