Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shouldn't std::pair<T1,T2> have trivial default constructor if T1 and T2 have?

I ran into a problem because

 std::is_trivially_default_constructible<std::pair<T1,T2>>::value == false;

even if

 std::is_trivially_default_constructible<T1>::value == true;
 std::is_trivially_default_constructible<T2>::value == true;

I failed to find a good reason for this design. Wouldn't it appropriate for std::pair<T1,T2> to have a =default constructor if T1 and T2 have?

Is there a simple work around (simpler than defining my own pair<>)?

like image 612
Walter Avatar asked Oct 27 '14 16:10

Walter


2 Answers

The simple reason is: history! The original std::pair<T0, T1> couldn't have a trivial default constructor as it had some other constructor. It was defined to initialize its members. Changing this behavior in std::pair<T0, T1> for trivially constructable types where people rely on the value getting initialized would be a breaking change.

In addition to the history reason, the default constructor of std::pair<...> is defined to be a constexpr constructor. A constexpr default constructor cannot be defaulted.

I'm not aware of a work-around other than creating a custom class.

like image 74
Dietmar Kühl Avatar answered Nov 08 '22 02:11

Dietmar Kühl


Default constructor of std::pair value-initializes both elements of the pair, first and second, so it can't be trivial.

like image 1
user396672 Avatar answered Nov 08 '22 02:11

user396672