Search code examples
c++destructorside-effectsdeep-copy

Side effects when passing objects to function in C++


I have read in C++ : The Complete Reference book the following

Even though objects are passed to functions by means of the normal call-by-value parameter passing mechanism, which, in theory, protects and insulates the calling argument, it is still possible for a side effect to occur that may affect, or even damage, the object used as an argument. For example, if an object used as an argument allocates memory and frees that memory when it is destroyed, then its local copy inside the function will free the same memory when its destructor is called. This will leave the original object damaged and effectively useless.

I do not really understand how the side effect occurs. Could anybody help me understand this with an example ?


Solution

  • That passage is probably talking about this situation:

    class A {
      int *p;
    public:
      A () : p(new int[100]) {}
      // default copy constructor and assignment
     ~A() { delete[] p; }
    };
    

    Now A object is used as pass by value:

    void bar(A copy)
    {
      // do something
      // copy.~A() called which deallocates copy.p
    }
    void foo ()
    {
      A a;  // a.p is allocated
      bar(a);  // a.p was shallow copied and deallocated at the end of  'bar()'
      // again a.~A() is called and a.p is deallocated ... undefined behavior
    }