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

Destructor of function argument called

本文关键字:析构函数 参数 函数 调用      更新时间:2023-10-16

以下是我所拥有的:

// 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的末尾调用。这是什么原因?或者我可能遗漏了什么?

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

如果你通过了:

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

然后不会复制A,因此在离开函数时不会对A进行析构函数调用。

如果A实现正确,则传递值版本不应进行核心转储。尽管要理解它为什么核心转储,我们还需要查看更多的代码。

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