C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Return Value Optimisation whenever you need it (guaranteed elision)

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sat, 15 Jul 2023 20:26:14 -0400
On Sat, Jul 15, 2023 at 7:58 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> We can return a mutex by value from a function as follows:
>
> std::mutex Func(void)
> {
> return std::mutex();
> }
>
> We can do this even though std::mutex can't be moved nor copied. This
> is called 'Return Value Optimisation', and it's mandatory for the
> compiler to elide the move/copy operation.
>
> But let's change it a little:
>
> std::mutex Func(void)
> {
> std::mutex mtx;
> return mtx;
> }
>
> Now it no longer compiles. What we have here is 'Named Return Value
> Optimisation'. In this circumstance, the compiler may elide the
> move/copy operation if it wants to, but still the move/copy
> constructor must be accessible -- therefore it won't work with an
> std::mutex.
>
> So this begs the question.... Is it at all possible to return a locked
> mutex by value from a function?

Here's a better question: is that a thing you should want? There are
good, reasonable reasons to want to be able to return non-moveable
objects. This is not one of them. Indeed, this is precisely the sort
of thing that people make objects non-moveable to *prevent* people
from doing.

There have been discussions of the right sort of syntax for this
functionality. P2025 went into some detail on the matter, but it
hasn't moved forward in a couple of years. From
https://github.com/cplusplus/papers/issues/756 it seems the committee
was not impressed by the idea.

I doubt that returning locked mutexes is the kind of example that
would change their minds.

Received on 2023-07-16 00:26:37