Create a deep copy of an array C++

后端 未结 4 888
迷失自我
迷失自我 2021-01-28 00:44

I am try to solve some problems in my program and it would appear that there is either a problem with my copy constructor or with my destructor. I am getting a memory exception.

相关标签:
4条回答
  • 2021-01-28 01:12

    That code doesn't make any sense. First you initialize your members to the values passed by the object to copy, through the initializer list. Then you allocate memory for the very same members and copy everything again.

    Most likely you are copying junk data into an uninitialized pointer. Get rid of the initializer list :readArray(a.readArray),arraysize(a.arraysize).

    0 讨论(0)
  • 2021-01-28 01:13

    You can't just memcpy random objects, you need to actually copy them with their copy operators.

    string most likely holds a pointer to heap-allocated storage. If you copy it bitwise, calling the destructor on the original string invalidates the "copied" string's data.

    Use something like std::copy to do this properly.

    #include <algorithm>
    ...
    std::copy(a.readArray, a.readArray+arraysize, readArray);
    
    0 讨论(0)
  • 2021-01-28 01:14

    I would not advice you to copy strings the way you do. As the string holds reference to heap memory you in fact copy the pointers and so the strings in both arrays are sharing memory. This is not very c++-ish and quite dangerous. I would advice you to use the assignment operator or copy constructors for the strings(yes do a cycle).

    0 讨论(0)
  • 2021-01-28 01:21

    The strings also have dynamic memory, so you'd have to go through each string and make a copy of it.

    A fix would be copying each string inside of your array instead of memcopy. The exception is from two different strings having the same pointer to a piece of memory and both trying to free it.

    0 讨论(0)
提交回复
热议问题