Destructor called when objects are passed by value

后端 未结 3 949
执笔经年
执笔经年 2021-02-14 06:00

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 cal

3条回答
  •  被撕碎了的回忆
    2021-02-14 06:53

    This is indeed because you didn't provide a copy constructor. Thus the compiler will generate one for you, which does trivial copy. And that's the trivial copy of the pointer that's problematic here.

    For the following declaration

    void SomeFunc(Sample x);
    

    There will be indeed a copy when you pass s1 to the function, but this copy will have a copy of the pointer, that is, the two object will point to the same int.

    Then, when exiting the function, the copy will be destroyed and will delete that pointer, leaving the original object in the calling code with a pointer just deleted (remember, they point to the same thing).

    Then, for the following declaration

    void SomeFunc(Sample &x);
    

    you don't have any copy, thus the problem doesn't show up. Indeed, passing by reference means that inside the function, the Sample object you're manipulating is exactly the same as the one you passed to the function, and won't be destroyed when the function exits.

提交回复
热议问题