0

How can I perform a deep copy with the following code? I have done some research but nothing has helped. I heard that I need to copy it recursively but how can i do that? most posts about deep copies show code similar to what I have so I can't see how the two are any different.

OtherClass<int>* arr = nullptr;
int size = 0;

public:
copyConstructor(const copyConstructor& src){
if (src.arr) {

    delete[] arr;

    size = src.size;

    arr = new OtherClass<int>[size];

    for (int i = 0; i < size; i++) {

        arr[i] = src.arr[i];

    }

} 

else {

    size = 0;

    arr = nullptr;

}
}
Exalino
  • 39
  • 6
  • 1
    related/dupe: https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three You can see your code and the answers are quite different – NathanOliver Oct 08 '19 at 19:19
  • Sidenote: Since a copy constructor creates a brand new object, you have to go out of your way (and be having a stupid moment) to self-assign in a copy constructor. `copyConstructor copy = copy;` should be setting off alarm bells in the ol' Mark I brain. `copy` has not been initialized yet, so what values does it contain that are worth copying? Personally I wouldn't test for it, and if I did, I'd write a nastygram to the log or console and then abort the program to force the programmer fix what's an obvious mistake. – user4581301 Oct 08 '19 at 19:37
  • Similarly, there can't possibly be a value of `arr` worth `delete`ing. – user4581301 Oct 08 '19 at 19:38
  • There is no need to recurse here. The loop is more than sufficient, but `std::copy` could save you from typing a few extra characters and maybe inserting a typo. – user4581301 Oct 08 '19 at 19:40
  • The else block is redundant because you've already initialized your data members to those values. – sweenish Oct 08 '19 at 20:58
  • If you replace your `OtherClass* arr` and all the angst it will bring with `std::vector> arr` you don't need any of the above. No copy/move constructors, assignment operators or destructor. – Ted Lyngmo Oct 08 '19 at 21:31
  • @NathanOliver I took a look at the link and noticed how they did the copy constructor but isn't that essentially what I did? but my above code performs a shallow copy instead. – Exalino Oct 09 '19 at 00:33
  • What class is the copy constructor supposed to belong to? Your code sample is incomplete. – sweenish Oct 09 '19 at 13:33

0 Answers0