这样难道不是内存泄露吗?
有以下程序:
#include <iostrream>
using namespace std;
class CAT
{
public:
CAT();
CAT(const CAT&);
~CAT;
int GetAge() const { return *itsAge;}
int GetWeight() const { return *itssWeight;}
void SetAge(int age) { *itsAge=age;}
private:
int *itsAge;
int *itsWeight;
};
CAT::CAT()
{
23 itsAge=new int;
itsWeight=new int;
*itsAge=5;
26 *itsWeight=9;
}
29 CAT::CAT(const CAT&rhs)
{
itsAge=new int;
itsWeight=new int;
*itsAge=rhs.GetAge();
34 *itsWeight=*(rhs.itsWeight);
}
CAT::~CAT()
{delete itsAge;
itsAge=0;
delete itsWeight;
itsWeight=0;
}
int main()
{
CAT frisky;
cout<<frisky.GetAge()<<endl
frisky.SetAge(6);
52 CAT boots(frisky);
cout<<frisky.GetAge()<<endl;
frisky.SetAge(7);
cout<<frisky.GetAge()<<endl
cout<<boots.GetAge()<<endl;
return 0;
}
输出为:
5
6
6
7
6
在23至26行为int型分配了内存空间,并用指针itsAge,itsWeight指向这两个空间。而在29至34的复制构造函数中又为int型重新分配了内存空间,而在这之前即23至26所分配的内存空间并没有释放掉,这样不就是产生了内存泄露吗?
另外52行的意思是不是表示“将frisky的成员变量复制到boots”?
还请大家指点!!!谢谢!