Regarding bitwise copying

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    Regarding bitwise copying

    Hi, I am confused regarding these concepts. Please clearify.

    1. Why is bitwise copying unsafe?
    2. Does copy constructor does bitwise copying?
    3. Is the main use of explicit copy constructor is to go for deep copying?

    Thanks in advance.
  • Girish Kanakagiri
    New Member
    • May 2007
    • 93

    #2
    Originally posted by bajajv
    Hi, I am confused regarding these concepts. Please clearify.

    1. Why is bitwise copying unsafe?
    2. Does copy constructor does bitwise copying?
    3. Is the main use of explicit copy constructor is to go for deep copying?

    Thanks in advance.
    1. bitwise copying will be unsafe, if you are putting some content on heap;
    I mean dynamically allocating memory and storing value for datamember.
    In this case bitwise copying is unsafe because both the pointers pointing to
    same memory location. If deleting of both the pointers clears the same piece
    of memory and leads to core dump.
    If data members are stored on stack then bitwise copying is totally safe.

    2. Default copy constructor does bitwise copying.

    3. If the data members are stored on heap, as explained in 1. then
    overloaded copy constructor is dealt with deep copying.

    Regards,
    Girish.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by bajajv
      1.Why is bitwise copying unsafe?
      2. Does copy constructor does bitwise copying?
      3. Is the main use of explicit copy constructor is to go for deep copying?
      Answer 1: The memory copied may contain objects that require a copy constructor in order to be copied. C++ does not use bitwise copy. Everything is memberwise copy.

      Answer 2: C++ does not use bitwise copy. You need to understand that the memberwise copy has already been made and the copy constructors of the data members have already been called before you get to the left brace of your copy constructor. You just get to correctly copy anything not already copied correctly, like pointers.

      Answer 3: Explicit constructors are just constructors that are marked to be called only by the programmer (i.e. explicitly). This has nothing to do with deep copy since an explicit copy constructor can't be called by the compiler in the first place.

      Originally posted by Girish Kanakagiri
      Default copy constructor does bitwise copying.

      3. If the data members are stored on heap, as explained in 1. then
      overloaded copy constructor is dealt with deep copying.
      This quote is not correct per my answers above. Also, it makes no difference where the data members are stored (stack oir heap). The same rules apply.

      Comment

      Working...