News for hackers. Stuff that matters.
Re:Const all the things? by kaashif on Monday January 24, 2022 @01:06PM (#30061413)
> 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

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

I admit I'm not really a C++ expert, so maybe I'm missing something.

Re:Const all the things? by PaulDavisThe1st on Monday January 24, 2022 @01:45PM (#30062020)
Yes, 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.
Re:Const all the things? by masklinn on Monday January 24, 2022 @03:05PM (#30063219)
RVO 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?