In C++ consider the two scenario,
- Returning object by reference.
- Returning object as it is.
In which of the above cases deep copying is done and Why?
Thanks in advance.
In C++ consider the two scenario,
In which of the above cases deep copying is done and Why?
Thanks in advance.
When an object is returned by reference, there is no copying of objects.
When an object is returned by value, a copy will be made. Whether that will be a shallow copy or a deep copy depends on the copy constructor.
Example 1
Simple struct
:
struct Point
{
double x;
double y;
double z;
};
You don't need to implement a copy constructor for such a struct
. The compiler will generate a correctly working copy constructor for it.
Example 2
struct Edge;
struct Vertex
{
std::list<Edge*> edges;
};
For Vertex
, the copy constructor generated by the compiler will copy the list of Edges
. This happens because the copy constructor of std::list
makes a deep copy. However, the deep copy ends there. It won't create new Edge
objects when making a copy of a Vertex
. If that is not adequate, you'll have to implement a copy constructor for Vertex
and do the right thing based on your need.
If an object has pointers to dynamically allocated memory, and the dynamically allocated memory needs to be copied when the original object is copied, then a deep copy is required.
A class that requires deep copies generally needs:
To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences.
Read this for more - Shallow vs. deep copying and How and When to Make Deep Copies in C++