samedi 1 septembre 2018

differences when using shared_ptr and unique_ptr to point to an array?

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.

  1. I must use <int []> for unique_ptr but <int> for shared_ptr only:

    unique_ptr myUniquePtr = unique_ptr ( new int[100]);

but

shared_ptr<int> mySharedPtr = shared_ptr<int>( new int[100]);

  1. for unique_ptr I do not need to overload a delete functor/lambda func for a pointer to an array

    unique_ptr myUniquePtr = unique_ptr ( new int[100]); //should be good enough

but I will need

shared_ptr< int> mySharedPtr = shared_ptr<int> ( new int [100], [](const int* p){delete [] p;});

  1. To access an element in the array through 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 are correct? Will it be different in C++14?

Best,

Aucun commentaire:

Enregistrer un commentaire