简体   繁体   中英

copying a c-style array to new memory

Writing a custom vector class (the underlying structure is a c-style array) and I can't wrap my head around the idea of copying the contents of an array into another new array (dynamically allocated) and then, after deleting the old pointer, simply redirecting it to the new pointer... doesn't that result in two pointers pointing to the same array? how does this get adequately destructed?

here's a snippet of what I'm referring to:

...
value_type* newarray = new value_type[new_capacity];
    for (size_t i{0}; i < size; ++i)
      newarray[i] = oldarray[i];
    delete[] oldarray; //makes sense
    oldarray = newarray; //so I've copied the starting address of the array to another address in memory?
    capacity = new_capacity;
 ...

so what happens to the newarray pointer? I understand that my old pointer is now pointing to newly allocated memory (and that the old memory is 'deleted') but surely there's another pointer in there somewhere still pointing to the same newly allocated memory?

The variable newarray is a locally created pointer variable. That just means a place called "newarray" is reserved on the stack to store the address of whatever newarray points to.

At the end of the function it will go out of scope and its memory will be reclaimed.The object it is pointing to will be unaffected.

It makes no difference how many pointers you have pointing at the same object just so long as the object they point to is deleted exactly once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM