通过值或引用调用时未调用构造函数/析构函数.不管怎样

Constructor/Destructor function not being called while calling by value or reference. Any way around it?

本文关键字:调用 构造函数 析构函数 不管怎样 引用      更新时间:2023-10-16

由于c++的一个特性,我遇到了麻烦。在处理了动态内存分配之后,由于明显的原因,我总是清除堆(空闲存储)。我用析构函数来实现。有时,使用构造函数来分配内存。但在从另一个函数调用对象(按值调用)之后,只有析构函数才能工作。我知道在很多情况下这是一个很好的功能。但是,在处理许多独立功能时,这很烦人。有办法绕过它吗,伙计们?或者,我应该只使用成员函数来分配和清除内存吗?

一个例子:

#include <iostream>
using namespace std;
class test{
int *a;
public:
test(int x) {a=new int;
             *a=x;}
int geta(){return *a;}
 ~test(){delete a;}
};
int apow2(test t)
{
return ((t.geta())*(t.geta()));
}
int main()
{
test tst(10);
cout<<"nA^2="<<apow2(tst);
//at this point, memory reference to 'a' doesn't exist
cout<<"n"<<tst.geta();
return 0;
}

您遇到了麻烦,因为您没有为类test实现复制构造函数副本赋值运算符:您没有遵守三规则。

但是,好消息!你不需要。你可以通过存储int而不是int*:来避免所有的混乱

class test
{
   int a;
public:
   test(int x)
     : a{x}
   {}
};

就是这样!没有动态分配,没有内存管理,什么都没有。只有test,还有一个int,它可以精确地存活test的寿命。完美的

如果你因为问题中没有说明的原因而需要动态分配(哇),那么你应该使用智能指针来为你管理它的生命周期:

class test
{
   std::unique_ptr<int> a;
public:
   test(int x)
     : a{new int(x)}
   {}
   int geta() { return *a; }
};

就是这样!没有内存管理,什么都没有。只有test,还有一个int*,它的指针可以精确地存活test的生命周期。完美的