C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::elide

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sat, 25 May 2024 20:40:42 +0100
On Sat, May 25, 2024 at 8:13 PM Lorand Szollosi wrote:
>
> Indeed - my point here was, if Frederick is okay with
> auto [v] = getLockedWhatever(); syntax, as in the
> example with get<> override, then getLockedWhatever
> can be a struct with a ctor and a public member.


I've been told time and time again, that no matter how good an idea
you have to change C++; your idea must achieve something that isn't
already possible, otherwise it isn't worth the time, effort, grief and
hassle of writing it into the Standard and having the compiler vendors
implement it.

So if we start off with the following program that needs NRVO:

    #include <mutex>
    using std::mutex;

    mutex Func(void)
    {
        mutex m;
        m.lock();
        return m; // compiler error
    }

    int main(void)
    {
        mutex m = Func();
    }

Well if you ask me whether this is already possible in C++, well I'd
have to say.... yes it is, if you use an "std::optional" as follows.
The std::optional can be a global variable with static duration, or it
can be on the heap, or on the stack, wherever you want it. As follwos:

    #include <cassert>
    #include <mutex>
    #include <optional>
    using std::mutex, std::optional;

    void Func(optional<mutex> &m)
    {
        assert( false == m.has_value() );

        try
        {
            m.emplace();
            m->lock();
        }
        catch(...)
        {
            m.reset();
            throw;
        }
    }

    int main(void)
    {
        optional<mutex> m;
        Func(m);
    }

Received on 2024-05-25 19:40:53