Why is the construction of std::optional more expensive than a std::pair?

后端 未结 4 617
死守一世寂寞
死守一世寂寞 2020-12-08 09:07

Consider these two approaches that can represent an \"optional int\":

using std_optional_int = std::optional;
using my_optional_int =         


        
4条回答
  •  情歌与酒
    2020-12-08 09:35

    Why does get_std_optional_int() require three mov instructions, while get_my_optional() only needs a single movabs?

    The direct cause is that optional is returned through a hidden pointer while pair is returned in a register. Why is that, though? The SysV ABI specification, section 3.2.3 Parameter Passing says:

    If a C++ object has either a non-trivial copy constructor or a non-trivial destructor, it is passed by invisible reference.

    Sorting out the C++ mess that is optional is not easy, but there seem to be a non-trivial copy constructor at least in the optional_base class of the implementation I checked.

提交回复
热议问题