Side effects when passing objects to function in C++

后端 未结 3 877
渐次进展
渐次进展 2021-01-13 05:40

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

Even though objects are passed to functions by means of the normal call-

3条回答
  •  天命终不由人
    2021-01-13 06:11

    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
    }
    

提交回复
热议问题