Add std::make_shared template specialization for std::enable_shared_from_this descendants.

73 views
Skip to first unread message

Andrew Dunn

unread,
Oct 10, 2014, 12:31:58 AM10/10/14
to ISO C++ Standard - Future Proposals Mailing List
At the moment, std::make_shared will call the constructor of an instance descended from std::enable_shared_from_this before initialising the self referential weak_ptr.

This makes it impossible to use shared_from_this() during the construction phase of the instance. The use case which I encountered is when constructing an instance which has member variables that keep a weak reference to the parent instance.

My proposal is to set the self-referential weak_ptr before calling the constructor. This would allow shared_from_this() to be used in the constructor.

In pseudocode it would look something like this:

namespace std
{
    template <typename T, typename... Params>
    enable_if_t<is_base_of<enable_shared_from_this<T>, T >::value,
                shared_ptr<T> >

    make_shared(Params&&... parameters)
    {

        ALLOCATE MEMORY
        CREATE SHARED POINTER TO ADDRESS
        SET SELF-REFERENTIAL WEAK POINTER
        T(parameters...);
        RETURN SHARED POINTER
    }
}

Any thoughts?

--
Andrew Dunn
Reply all
Reply to author
Forward
0 new messages