1

Just a quick query regarding shared_ptr:

so i have this code:

std::shared_ptr<int> asd(new int[10]);

From my understanding, i am making a single shared_ptr<int> that points to an array of 10 integers. if my understading is correct then here are my questions:

1.) How do i access the values/initialize ?

2.) Is it possible to use make_shared?

3.) What if i want to make an array of 10 shared_ptr and make them point to a single int?

I am also aware that i need to supply a custom deleter when i deal with arrays using shared_ptr. Using vectors will also make it easier.

Carlos Miguel Colanta
  • 2,685
  • 3
  • 31
  • 49

1 Answers1

4
  1. This is a very very bad idea. You are creating indeed an array of 10 ints, but the default deleter uses delete instead of delete[] to deallocate the memory. You either have to specify a custom deleter,

    std::shared_ptr<int> asd(new int[10]{0}, [](int* _p)
    {
        delete[] _p;
    }); // also zero-initializes
    

    or use

    std::unique_ptr<int[]> asd(new int[10]{0}); // no need for a deleter here
    

    instead, as unique_ptr has an array specialization, and the deleter uses the proper delete[] for this specialization. The examples above zero-initialize the dynamically allocated arrays. If you want other values, then dereference the pointers and set the values, as you'd do in a raw pointer situation. To access the value in the array pointed by a shared_ptr, you cannot use arr[j] syntax anymore, as shared_ptr does not overload operator[]. You need to get the managed raw pointer and use it like

    *(asd.get()+2) // this dereference the third element
    

    or

    asd.get()[2] // same as above
    

    As you can see, shared_ptr is not really made for arrays. On the other hand, unique_ptr overloads operator[] for its managed array, so you can simply use asd[2] to refer to the third element in the array.

  2. You cannot use make_shared, as make_shared does not allow you to specify the deleter.

  3. Simply create an array of 10 shared_ptr from an initial shared_ptr that points to your desired int

    std::shared_ptr<int> sp(new int{42});
    std::array<std::shared_ptr<int>, 10> arr_sp;
    for(auto& elem: arr_sp)
        elem = sp;
    

    DO NOT construct all elements of the array from the same raw pointer, as you end up with multiple shared_ptrs managing the same raw pointer, which is always a bad idea.

vsoftco
  • 55,410
  • 12
  • 139
  • 252