Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Doing a deep copy in C++?
I am working on a homework assignment and I can not figure out how to do deep copies. I need to do a deep copy a class(group) of arrays and cannot find an example of how that works.
1 Answer
- husoskiLv 72 years ago
It would help a whole bunch if you showed declarations of the types of "arrays" you need to copy and how they are grouped into "classes".
The word "array" has at least two specific meanings in C++: the primitive array type inherited from C; and the template type std::array<T,size_t> defined in the <array> header. It's also used colloquially sometimes to refer to std::vector<> objects, but that's less common. The actual declarations would clear this up.
A "deep copy" means duplicating an entire data structure. For nested array-like structures, tree-type structures and other acyclic graphs, or anything else without recursive references; the general idea is easy. Copy simple data directly and use "deep copy" functions or constructors to copy any objects with internal structure that needs to be duplicated.
Standard C++ collection classes will do much of that automatically. If you've implemented a matrix as a vector of vectors (std::vector<std::vector<double>> for example) then assignment or initialization of a new object will do a deep copy automatically. I cooked up a sample of that here:
If you have your own collection/container types, you'll have to create your own constructor, assignment operator and/or "factory method" to do something similar.