From what I know smart pointer should be equilvalent to “raw” pointer with the difference that it is safe. Ok, but if I have regular pointer:
int* p = new int[10];
fill(p, p + 10, 0);//this will work for regular pointer but not for smart one.
Same with hand written loop:
for(int i = 0; i < 10; ++i)
{
*p[i] = 0;
}
This is not possible (I think) for smart poiner. So the question is, how can I initialized array to which pointer I have stored in one of smart pointers (let’s assume shared_ptr)?
First off, it might be easier just to use
std::vector<int>. If your array has an unchanging size, though, then perhapsstd::vector<int>is indeed better replaced with a smart pointer.With that out of the way, your first choice should be a
std::unique_ptr, specifically the array specialization:std::unique_ptr<int[]>. (If you don’t, the smart pointer will usedeleteinstead ofdelete[]on your pointer, leading to undefined behavior.) Your code would become:As you can see, smart pointers have a
get()method that returns the underlying pointer.From here, if you need to use a
std::shared_ptr, things become a big dangerous (do to unfortunate oversight, as far as I know). That oversight is thatstd::shared_ptrhas no array specialization:However,
std::shared_ptrcan easily correct this like so:From this point, the code is the same:
Note that
std::shared_ptrprovides a constructor to construct from astd::unique_ptr, which properly uses the deleter. So this is safe: