调用了函数参数的析构函数
Destructor of function argument called
以下是我所拥有的:
// 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
。所以函数中的mystruct
是main
中的副本。因此,当程序流离开函数时,会对其调用析构函数。
如果你通过了:
- 按指针:
B *foo(const A *mystruct)
或 - 参考:
B *foo(const A &mystruct)
然后不会复制A
,因此在离开函数时不会对A
进行析构函数调用。
如果A
实现正确,则传递值版本不应进行核心转储。尽管要理解它为什么核心转储,我们还需要查看更多的代码。
当您调用foo
时,会通过调用复制构造函数从*mystruct
构造一个临时对象。当您从foo
返回时,临时对象将被销毁。核心转储是由A
中的内存管理不当引起的。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 什么时候调用析构函数
- 优先顺序:智能指针和类析构函数
- C++-明确何时以及如何调用析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- 重载运算符new[]的行为取决于析构函数
- 我需要知道编译器如何在cpp中使用析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- C++:显式调用模板参数的 typedef 的析构函数
- 从析构函数访问模板类构造函数的参数,可以吗?
- 为什么析构函数不接受C++中的参数?
- 为什么在将对象作为参数传递时调用析构函数而不调用构造
- 为什么析构函数在对象引用作为参数传递时函数范围结束后调用
- 传递到虚拟析构函数的这个额外参数是什么?
- 取消分配(并调用的析构函数)模板参数
- 调用了函数参数的析构函数
- 析构函数参数