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

核能气质少年 提交于 2019-12-04 02:49:08

问题


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<>)?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/26591957/shouldnt-stdpairt1-t2-have-trivial-default-constructor-if-t1-and-t2-have

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!