Вопрос

Consider this code:

using namespace std;

int* get()
{
    unique_ptr<int> p (new int[4]);
    return p.get();
}
int main(int argc, char **argv)
{
    int *arr1=get();
    int* arr2=get();
    for(int i=0;i<4;i++)
    {
        arr1[i]=i;
        arr2[i]=i*2;
    }
    for(int i=0;i<4;i++)
        cout << arr1[i];
    return 0;
}

arr1 and arr2 point to the same area of memory. So they share the same values. I don't understand why, when I call arr2=get() :

unique_ptr<int> p (new int[4]);

This object shouldn't be created again? It isn't deleted because still reachable by arr1. How to get two arrays of different memory areas?

Нет правильного решения

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top