When is it appropriate to use std::optional
Asked Answered
I

1

5

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.

Irs answered 29/4, 2019 at 6:35 Comment(0)
A
11

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.

Allhallowtide answered 29/4, 2019 at 6:40 Comment(3)
Not to mention unique_ptr forces dynamic allocation when there's no good reason to do so for this use case.Tavern
Thank you for the information & help! The unique_ptr is being used to achieve RAII with WINAPI handles with a custom deleter. The function either opens the handle or returns std::nullopt via std::optional.Irs
Ah, so the std::unique_ptr isn't meant to wrap around the uint32_t? Sorry, then I understood the last part of your question incorrectly. Using std::unique_ptr as a RAII wrapper with a custom deleter is absolutely fine!Allhallowtide

© 2022 - 2025 — McMap. All rights reserved.