C++ Logo

std-proposals

Advanced search

Re: [std-proposals] int Func(void) noreentry(-1)

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Fri, 17 Feb 2023 14:15:30 +0000
On Fri, Feb 17, 2023 at 12:50 PM Edward Catmur <ecatmur_at_[hidden]> wrote:
>
> A moved from object doesn't own a lock.


I see what you mean now. The problem is that the 'moved from' object
will contain a 'unique_ptr' which is set to nullptr. We would have to
put the 'unique_ptr' inside a 'create_on_demand', something like:

#include <utility> // declval

template<class SmartPtr>
class create_on_demand : public SmartPtr {

    void create_if_necessary(void) noexcept(false)
    {
        if ( nullptr == this->SmartPtr::get() )
        {
            this->SmartPtr::reset(new SmartPtr::element_type);
        }
    }

public:
    using SmartPtr::SmartPtr;

    SmartPtr::pointer get(void) const // can't override
    {
        this->create_if_necessary();
        return this->SmartPtr::get();
    }

    explicit operator bool() const // can't override
    {
        this->create_if_necessary();
        return true;
    }

    SmartPtr::element_type &operator*(void) const
noexcept(noexcept(*std::declval<SmartPtr::pointer>())) // can't
override
    {
        this->create_if_necessary();
        return this->SmartPtr::operator*();
    }
};


> So they share a lock. Presumably there are use cases for only being able to use
> one object at a time, for a set of objects linked in this way.


Fair enough. Although I think it should be more explicit that just
using the copy constructor. There should be a keyword for linking
objects:

    MyClass obj1;
    MyClass obj2( noreentry_linked_to obj1 ); // This uses shared_ptr
so that multiple objects share one mutex
    MyClass obj3( obj1 ); // This creates a new mutex

Received on 2023-02-17 14:15:42