4 ms·
> for performance-oriented code, the original example, where the argument is stack-allocated in the caller, passed by reference, and used based on the return va
by kaashif 5y ago
> for performance-oriented code, the original example, where the argument is stack-allocated in the caller, passed by reference, and used based on the return value, has benefits that can't be replicated in the std::optional<> version.
Can you go into detail? What are the benefits that can't be replicated?
If anything, the std::optional version seems better, since we can avoid an invocation of the SomeType constructor. Otherwise, everything is the same - everything's allocated on the stack, there is no dynamic allocation.
> If an optional<T> contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined.
That's from here: https://en.cppreference.com/w/cpp/utility/optional https://en.cppreference.com/w/cpp/utility/optional
Since C++17, RVO is required by the standard too:
> Return value optimization is mandatory and no longer considered as copy elision; see above.
From here: https://en.cppreference.com/w/cpp/language/copy_elision https://en.cppreference.com/w/cpp/language/copy_elision
I admit I'm not really a C++ expert, so maybe I'm missing something.
- PaulDavisThe1st 5y agoYes, in C++17, RVO would fix the issue. Alas, some of us are stuck with project conventions that have not reached "use C++17". Without RVO, there's an extra copy.
- masklinn 5y agoRVO is not new in C++17 though, only the standard requiring it in some cases. Unless your compiler is truly ancient odds are good it RVOs just fine no?