I was wondering if this would be considered a valid usage of std::optional. I have a function that returns a process_id
(std::uint32_t
value), would it be more efficient to have a standard "std::uint32_t
" function that returns 0 if we fail to find the target processes ID or would returning a std::optional be more appropriate?
example:
std::optional<std::uint32_t> FindProcessID(std::string_view process)
{
bool find = false;
if (!find)
// we fail to find the process_id and return nothing.
return std::nullopt;
else if (find)
return 100; // return the id
}
I am also doing this when returning a unique_ptr as-well opposed to just returning a nullptr, but I am unsure if this would be considered "abuse" of said feature, and if it would be better just to return 0 and check for that value. Thank you in advance.
As a conclusion, std::optional is as efficient as a custom type to represent an optional integer value. Don't implement your own type, simply use the standard type.
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 .
Abstract. std::optional is an important vocabulary type in C++17. Some uses of it are verbose and would benefit from operations which allow functional composition. I propose adding transform, and_then, and or_else member functions to std::optional to support this monadic style of programming.
C++17 introduced std::optional<T> which lets you augment the values of a type T with a bonus value known as std::nullopt which semantically represents the absence of a value. A std::optional which holds the value std::nullopt is known as empty.
I was wondering if this would be considered a valid usage of
std::optional
Yes, yes, yes - this is what std::optional
is for!
would it be more efficient to return 0 if we fail
Technically yes, std::optional
is a wrapper, so it comes with a tiny overhead. The likelihood that this is a performance bottleneck in your code is, however, extremely low. If unsure, create a benchmark and compare the two versions of your function.
I am currently doing this when returning a unique_ptr as-well, but I am unsure if this would be considered "abuse" of said feature
This is indeed not the intended, idiomatic use case for std::unique_ptr
. Readers of your code would expect the std::unique_ptr
to handle exclusive ownership of some (possibly polymorphic) object. Neither are there many valid scenarios to put a primitive integral type into a smart pointer, nor is it good practice to use std::unique_ptr
for a use case that's perfect for std::optional
.
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