0

I'm currently learning smart pointers and I have some trouble transitioning from "normal" pointers. I would like to know if it's possible to return a shared_ptr from a function that points to an element inside an shared_ptr array?

In the main function I have declared an int array:

shared_ptr<int[]> arr(new int[size]);

The function that I would like to create would return a shared_ptr to the smallest element of the array:

shared_ptr<int> getSmallestElement(shared_ptr<int[]> arr, int size) {
    int smallestValue = arr[0], smallestIndex = 0;
    for (int i = 1; i < size; i++) {
        if (smallestValue > arr[i]) {
            smallestValue = arr[i];
            smallestIndex = i;
        }
    }
    // what would be the equivalent shared_ptr code for the code below?
    int *returnPointer = arr[smallestIndex];
    return returnPointer;
}

The closest I got, but this is using my logic of normal pointers, was:

  shared_ptr<int> returnPointer = arr.get() + smallestIndex;
  return returnPointer;

Is it even possible to do this with a shared_ptr or is the preferred way using unique_ptr?

Nedzad
  • 13
  • 1
  • 1
    You probably want to use `std::array` or `std::vector` instead of `int[]`. – πάντα ῥεῖ Mar 07 '19 at 18:55
  • @KamilCuk I should have worded my question better, sorry about that. But the function needs to return a pointer to the existing element. So there would be no need for new int. – Nedzad Mar 07 '19 at 18:57

1 Answers1

3

You need to use the aliasing constructor, so that the ownership relation is maintained:

shared_ptr<int> returnPointer{arr, *arr + smallestIndex};

Note that you cannot use subscript operator with the shared pointer directly. You need to indirect it first so that the subscript operator applies to the array: (*arr)[i]

eerorika
  • 232,697
  • 12
  • 197
  • 326