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?
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.
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 .
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>>);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With