std::optional - construct empty with {} or std::nullopt?

前端 未结 4 938
眼角桃花
眼角桃花 2020-12-06 04:22

I thought that initializing a std::optional with std::nullopt would be the same as default construction.

They are described as the same at cppreference, as form (1)<

4条回答
  •  半阙折子戏
    2020-12-06 04:26

    In this case, {} invokes value-initialization. If optional's default constructor is not user-provided (where "not user-provided" means roughly "is implicitly declared or explicitly defaulted within the class definition"), that incurs zero-initialization of the entire object.

    Whether it does so depends on the implementation details of that particular std::optional implementation. It looks like libstdc++'s optional's default constructor is not user-provided, but libc++'s is.

提交回复
热议问题