I would like to ask how to return an std::optional
in an efficient way and I would like to use std::make_optional()
.
For example lets have this code snippet:
std::optional<Path> CreateCanonicalPath(const std::string_view& path)
{
std::error_code errorCode;
const auto result = std::filesystem::weakly_canonical(std::filesystem::u8path(path), errorCode);
return !errorCode ? std::make_optional(result) : std::nullopt;
}
I am particularly interested whether there is any optimization in passing result
to std::make_optional
. Would it be better to use std::make_optional(std::move(result))
?
And does it prevent any RVO or NVRO?
The result
is a local variable but it is not exactly in a return statement so I assume the compiler can't use move by itself.
weakly_canonical
will be slowest part since it interacts with OS. – Saritastd::path
withstd::optional
? What is the difference between a returned emptyoptional
and emptypath
in case of errors? AFAIK,optional
is used mainly for types that themselves don't provide an "empty" state (such as integers), or where the empty state may be a valid result (such as withstd::string
). – Featherweightstd::filesystem
. – Indeterminacymake_optional()
is a factory pattern, it may allow to use some optimizations. For examplemake_shared()
does it and it is kind of significant. I don't think it is the case formake_optional()
but I like to have it consistent with othermake_...()
functions. – Indeterminacy