← Back to context

Comment by Maxatar

2 months ago

You seem to misunderstand the meaning of deep versus shallow copy. This distinction has to do with how references/pointers get copied.

In C++ the compiler generated copy constructors are shallow, not deep, meaning that if you want a copy to reconstruct the object being pointed to, you can not use the default copy constructor but need to supply your own explicit copy constructor to do so.

No - you are confusing C and C++.

In C a structure passed by value will just be shallow-copied.

In C++ a structure/class passed by value will by copied using whatever copy constructor is defined by the structure type. If there is no explicitly defined copy constructor, then a default copy constructor will be used that does member-wise copy using the member's copy constructors.

So, unless you have chosen to shoot yourself in the foot by defining a class who's copy constructor doesn't do a deep copy, then C++ pass-by-value will indeed do a deep copy.

The case of a structure with a pointer member (e.g. maybe you defined your own string class) is certainly one where you would need to define an appropriate copy constructor, and not doing so would indeed be shooting yourself in the foot.

  • >So, unless you have chosen to shoot yourself in the foot by defining a class who's copy constructor doesn't do a deep copy, then C++ pass-by-value will indeed do a deep copy.

    You either are misspeaking, deeply confused, or quite possibly both.

    • Do you agree that C++ pass-by-value is using copy constructors?

      Do you agree that the copy constrictors of the C++ standard library (STL) all do deep copy?

      Do you agree that if you write your own class with a raw pointer member, you would need to write a copy constructor?

      So, what exactly are you disagreeing about ?!

      You seem to be saying that if you wrote a C-style structure (no constructors) with a pointer member, then C++ would behave like C, which is true, but irrelevant. We're talking about C++ vs C, but since C++ is a superset of C, then yes you can still screw yourself C-style if you choose to.

      2 replies →