samedi 14 mai 2022

Question about the declaration about the aliasing constructor for `std::shared_ptr`

I think the 8th constructor of the std::shared_ptr<T> should be decalared as

template< class T, class Y >
shared_ptr<T>( const shared_ptr<Y>& r, element_type* ptr ) noexcept; 

other than

template< class Y >
shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;

Sorry for my poor English, this code snippet may make the question more clear to you:

#include<memory>
#include<vector>

struct Widget
{
    std::vector<int> vec;
    int var;
};

int main()
{
    auto wp{std::make_shared<Widget>(std::vector<int>{1,2,3}, 69)};

    std::shared_ptr<std::vector<int>> vp{wp, &wp->vec};
}

You see, vp is std::shared_ptr<vector<int>>, whereas wp is std::shared_ptr<Widget>. So, I think the declaration for the said constructor should be template< class T, class Y > other than shared_ptr<Y>.

ADDED:Why I want to make such modification for the said declaration? I just want to emphasise that the type of the aliasing constructor constructed(i.e. shared_ptr<T>) is different from the object which is passed as parameter. (i.e. the type of the argument is shared_ptr<Y>).

NOTE: As per the document, the 8th constructor is avilable in C++11, but it seems that the code sinppet above does not compile with C++11, so I have to set the compilation option to C++20. And the tag for this post is still C++11, not a clerical error. If I am wrong, please let me know.

Aucun commentaire:

Enregistrer un commentaire