gpt4 book ai didi

c++ - 动态内存分配、指针成员和析构函数

转载 作者:太空狗 更新时间:2023-10-29 20:23:35 25 4
gpt4 key购买 nike

我编写了以下虚拟类来了解复制构造函数、复制赋值运算符和析构函数的工作原理:

#include <string>
#include <iostream>

class Box {

public:
// default constructor
Box(int i=10,const std::string &t=std::string()) : a(i),s(new std::string(t)) {}
// copy constructor
Box(const Box &other) { a=other.a; s=new std::string(*other.s); }
// copy assignment operator
Box &operator=(const Box &other) { a=other.a; s=new std::string(*other.s); }
// destructor
~Box() { std::cout<<"running destructor num. "<<++counter<<std::endl; }
int get_int() { return a; }
std::string &get_string() { return *s; }
private:
int a;
std::string *s;
static int counter;

};

int Box::counter=0;

我在我的代码中使用此类类型来测试它是如何工作的,但我在考虑销毁具有内置指针类型成员的对象的含义:

#include "Box.h"

using namespace std;

int main()
{
Box b1;
Box b2(2,"hello");
cout<<b1.get_int()<<" "<<b1.get_string()<<endl;
cout<<b2.get_int()<<" "<<b2.get_string()<<endl;
Box b3=b1;
Box b4(b2);
cout<<b3.get_int()<<" "<<b3.get_string()<<endl;
cout<<b4.get_int()<<" "<<b4.get_string()<<endl;
b1=b4;
cout<<endl;
cout<<b1.get_int()<<" "<<b1.get_string()<<endl;
{
Box b5;
} // exit local scope,b5 is destroyed but string on the heap
// pointed to by b5.s is not freed (memory leak)
cout<<"exiting program"<<endl;
}

此指针在构造函数中初始化为指向空闲存储上的(始终是新的)动态分配的内存。因此,当调用析构函数时,要销毁的对象的成员将以相反的顺序销毁。在这种情况下是否正确,只有 int 和指针对象被销毁,我最终会发生内存泄漏(堆上的字符串未被释放)?

另外,定义这个复制赋值运算符,我每次赋值一个对象时,是否都会发生内存泄漏(指针指向堆上的新对象,前者丢失了是吗?)?

最佳答案

每次调用 new 时,都必须删除它(共享指针除外)。

所以你必须在析构函数中删除字符串。

赋值运算符适用于现有实例,因此您已经创建了 s 并且不必为 s 创建新字符串。

析构函数析构它的成员。由于指针就像一个 int,只有保存地址的变量被破坏,而不是它指向的对象。

是的,在每个对象中都会有内存泄漏,并且每次您按照设计类的方式使用赋值运算符时。

关于c++ - 动态内存分配、指针成员和析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32477477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com