Thursday, February 17, 2011

A shallow copy , Deep Copy and Smart Pointer

A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. 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 disasterous consequences.

Smart Pointer

The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. You can find it in the header .

Automatic cleanup don't need to remember to free the pointer,
Automatic initialization don't need to initialize the auto_ptr to NULL
Dangling pointers a pointer that points to an object that is already deleted

Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose.

2 comments:

  1. The purpose of the copy constructor and the assignment operator are almost equivalent — both copy one object to another. However, the assignment operator copies to existing objects, and the copy constructor copies to newly created objects.

    The difference between the copy constructor and the assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

    * If a new object has to be created before the copying can occur, the copy constructor is used.
    * If a new object does not have to be created before the copying can occur, the assignment operator is used.

    There are three general cases where the copy constructor is called instead of the assignment operator:

    1. When instantiating one object and initializing it with values from another object (as in the example above).
    2. When passing an object by value.
    3. When an object is returned from a function by value.

    In each of these cases, a new variable needs to be created before the values can be copied — hence the use of the copy constructor.

    Because the copy constructor and assignment operator essentially do the same job (they are just called in different cases), the code needed to implement them is almost identical.

    ReplyDelete
  2. The default copy constructor and default assignment operators it provides use a copying method known as a shallow copy (also known as a memberwise copy).

    ReplyDelete