Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
//Why this work well
    dvector(size_t size)
        :_size(size),
        _data(nullptr)
    {
    }
//But this generate the error "no matching function for call to 'construct_at"

    dvector(size_t size)
        :_size(size)
    {
        _data = std::make_shared<T>( new T[size] );
    }    

//This generate no errors // WHY???
    dvector(size_t size, T* temp)
        :_size(size)
    {
        _data = std::make_shared<T>(temp);
    }    


What I have tried:

dvector is templated class. I want to store arrray as shared_ptr
What do for it to work?
Posted
Updated 23-Sep-22 14:30pm
Comments
Greg Utas 23-Sep-22 15:14pm    
What is the type of T in the second constructor? T is a parameter to the third constructor but not the second.
Greg Utas 23-Sep-22 15:20pm    
You're allocating an array in the second constructor. I've done that with unique_ptr<T[]>, but the first answer to this post says that it's not a good idea for shared_ptr:
https://stackoverflow.com/questions/39142343/wrap-dynamic-array-with-shared-ptr-by-make-shared

And here's another post:
https://stackoverflow.com/questions/13794447/can-you-allocate-an-array-with-something-equivalent-to-make-shared

1 solution

There are a few different ways this can be done. Here's one :
C++
_data = std::make_shared( new T[ size ]() );
I think that will work but it is hard to know for sure because the declaration of _data is not shown. You do not need to null it in your first case because that happens automatically. If your compiler does not support this specialization for arrays then enable C++17 capabilities.

Is there a reason you don't use a vector? This is exactly what it is for.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900