Side effects when passing objects to function in C++

后端 未结 3 846
渐次进展
渐次进展 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:05

    Here is another example. The point is that when the callee (SomeFunc) parameter destructor is invoked it will free the same object (ptr) pointed to by the caller argument (obj1). Consequently, any use of the caller argument (obj1) after the invocation will produce a segfault.

    #include 
    using namespace std;
    
    class Foo {
    public:
        int *ptr;
    
        Foo (int i) {
            ptr = new int(i);
        }
    
        ~Foo() {
            cout << "Destructor called.\n" << endl;
            //delete ptr;
        }
    
        int PrintVal() {
            cout << *ptr;
            return *ptr;
        }
    };
    
    void SomeFunc(Foo obj2) {
        int x = obj2.PrintVal();
    } // here obj2 destructor will be invoked and it will free the "ptr" pointer.
    
    int main() {
        Foo obj1 = 15;
    
        SomeFunc(obj1);
    
        // at this point the "ptr" pointer is already gone.
        obj1.PrintVal();
    }
    

提交回复
热议问题