函数参数的析构函数被调用

时间:2014-04-30 22:15:29

标签: c++ delete-operator

这就是我所拥有的:

// define structures A & B...
// Brief example of the functions:
struct B* foo(const struct A mystruct)
{
    struct B *outstruct = new S();
    // Copying values from structure A to B
    return(outstruct);
}
int main()
{
    struct A *mystruct = new A();
    struct B *tmp = foo(*mystruct);
    delete(A); delete(B);
    return 0;
}

我一直收到核心转储消息,所以我在A的析构函数中放了一个printf语句。它表明析构函数被调用了两次:(1)在main的末尾,如预期的那样,和(2)在foo结束。

因此,我更改了foo函数以将mystruct作为指针传递(进行必要的语法更改),并且根据需要在main的末尾仅调用析构函数一次。这是什么原因?或者我可能会遗漏其他东西?

2 个答案:

答案 0 :(得分:1)

函数struct B* foo(const struct A mystruct)按值传递A。因此,函数中的mystructmain中的B *foo(const A *mystruct)的副本。因此,当程序流离开函数时,就会调用析构函数。

如果您通过:

  • 通过指针:B *foo(const A &mystruct)
  • 参考:A

然后没有复制A,因此在离开函数时没有析构函数调用A

如果{{1}}被正确实现,那么按值传递版本不应该是核心转储。虽然要了解核心转储的原因,但我们需要查看更多代码。

答案 1 :(得分:0)

当您调用foo时,通过调用复制构造函数从*mystruct构造临时对象。从foo返回时,临时对象将被销毁。核心转储是由A中的错误管理内存引起的。

相关问题