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?