I want to create some continuous memory, and use bunch of shared_ptr pointing to them.
int main() {
int *arr = new int[5];
for (int i = 0; i < 5; i++) {
std::shared_ptr<int> ptr(&arr[i]);
}// when the loop scope end, the shared_ptr will be destroyed.
};
this code will give an error:
pointer being freed was not allocated
my expectation: when the scope of loop end, the shared_ptr will be destroy, and the element in array will be destroyed successively.
But it seems that when the first pointer is destroyed, the whole array is freed.
I also tried std::allocator
, still not work.
So is there any way that can allocate continuous memory, and I can use shared_ptr pointing to each of them, then when the first element is freed, the whole memory won't be freed together?