Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can defaulted default constructors throw?

Tags:

c++

c++11

Defaulted default constructors are generated by the C++ compiler, the user has no control over them. Can they throw? Is it ok to specify noexcept when declaring one?

The following code compiles fine with gcc.

struct A
{
  A() = default;
};

struct B
{
  B() noexcept = default;
};

int main()
{
  A a;
  B b;

  return 0;
}
like image 253
user1095108 Avatar asked Feb 09 '14 14:02

user1095108


People also ask

What is a defaulted default constructor?

A type with a public default constructor is Default Constructible; Do you want to learn how we define a Defaulted Default Constructor? In the definition of a default Constructor, class_name must name the current class or current instantiation of a class template.

Does the default constructor have an exception specification?

The implicitly-declared (or defaulted on its first declaration) default constructor has an exception specification as described in dynamic exception specification (until C++17) exception specification (since C++17)

What happens when you default construct a function?

With the latter, the function becomes "user-provided". And that changes everything. If you attempt to default construct one, the compiler will generate a default constructor automatically. Same goes for copy/movement and destructing.

When is the default constructor for Class T trivial?

The default constructor for class T is trivial (i.e. performs no action) if all of the following is true: The constructor is not user-provided (i.e., is implicitly-defined or defaulted on its first declaration)


2 Answers

It is allowed to add a noexcept specifier to a defaulted special member function (default constructor, copy-constructor, assignment-operator etc.).

A default declared special member function will have a noexcept specifier depending on the noexcept specifiers of the involved functions (its implicit noexcept specifier). If you explicitly specify noexcept compilation should fail if this conflicts with the implicit noexcept specifier.

like image 96
pmr Avatar answered Nov 01 '22 11:11

pmr


can default constructors throw?

Yes, they can. For example, if the class has data member(s) whose default constructor throws.

struct Foo
{
  Foo() { /* throws */} 
};

struct Bar
{
  Bar() = default;
  Foo f;
}
like image 41
juanchopanza Avatar answered Nov 01 '22 12:11

juanchopanza