Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of `std::make_optional`

All the std::make_ are made redundant by C++17 with the introduction of Class template argument deduction (except make_unique and make_shared).

So what is the point of std::make_optional? As far as I can tell it does the exact same thing as the deduction guides for std::optional.

Is there a scenario where std::make_optional is preferred over deduction guides?

like image 562
bolov Avatar asked Jul 04 '20 22:07

bolov


People also ask

What is the purpose of std :: any?

std::any Class in C++ any is one of the newest features of C++17 that provides a type-safe container to store single value of any type. In layman's terms, it is a container which allows one to store any value in it without worrying about the type safety.

Does STD optional allocate memory?

What's more, std::optional doesn't need to allocate any memory on the free store. std::optional is a part of C++ vocabulary types along with std::any , std::variant and std::string_view .


1 Answers

One example of the difference is when you want (for whatever reason) to make an optional containing an optional:

#include <optional>
#include <type_traits>

int main()
{
    auto inner=std::make_optional(325);
    auto opt2=std::make_optional(inner); // makes std::optional<std::optional<int>>
    auto opt3=std::optional(inner);      // just a copy of inner
    static_assert(std::is_same_v<decltype(opt2), std::optional<std::optional<int>>>);
    static_assert(std::is_same_v<decltype(opt3), std::optional<int>>);
}
like image 155
Ruslan Avatar answered Sep 20 '22 07:09

Ruslan