Why is std::pair not nothrow constructible?

810 Views Asked by At

The following code:

#include <iostream>
#include <iomanip>
#include <string>
#include <utility>
using namespace std;

struct Foo
{
    std::string s;
    int i;
};

int main()
{
    cout << boolalpha << is_nothrow_constructible<Foo>::value << endl;
    cout << is_nothrow_constructible<pair<string, int>>::value << endl;

    cout << is_nothrow_move_constructible<Foo>::value << endl;
    cout << is_nothrow_move_constructible<pair<string, int>>::value << endl;

    return 0;
}

produces the following output when compiled with g++ -std=c++11:

true
false
true
true

Why is std::pair<string, int> not nothrow constructible, while Foo is, and why it is nothrow move constructible?

2

There are 2 best solutions below

0
On

Interestingly enough, none of the constructors is declared noexcept under any conditions. Likely a typical Standard defect (only the textual description below promises to not throw any exceptions if none of the elements does.)

5
On

Usually, defaulted constructors are defined as noexcept whenever possible. However, std::pair has default constructor defined without noexcept (i.e. not nothrow). You can check it yourself here.

You can see the default constructor for std::pair is defined without noexcept (first item from the link), and move constructor for std::pair is defaulted (8th item from the link).

Since you have not declared/defined any constructor for Foo, its constructors are defaults, therefore noexcept.