In C++11, I just found that it looks like there are some differences between shared_ptr and unique_ptr when they are used to allocate an array. I would like to get confirmation if what I found is correct.
I must use <int []> for unique_ptr but <int> for shared_ptr only:
unique_ptr<int []> myUniquePtr = unique_ptr<int[]> ( new int[100]);
shared_ptr<int> mySharedPtr = shared_ptr<int>( new int[100]);
For unique_ptr, I do not need to overload a delete functor/lambda func for a pointer to an array:
unique_ptr<int []> myUniquePtr = unique_ptr<int[]> ( new int[100]); //should be good enough
but I will for shared_ptr:
shared_ptr< int> mySharedPtr = shared_ptr<int> ( new int [100], [](const int* p){delete [] p;});
To access an element in the array through a smart pointer, with unique_ptr I can use the regular way [index], but with shared_ptr I cannot do that:
myUniquePtr[10] = 100; // should be OK
but I need
mySharedPtr.get()[10] = 100;
Could you please confirm if the above statements are correct? Will it be any different in C++14?
uinque_ptrhas a specialisation for array types, wherefore it can discern whether it needs to usedeleteordelete[]without you providing the deleter. However, if you need to allocate an array and have the respective accessors, you probably want to usestd::vectororstd::arrayinstead.make_uniqueandmake_shared.