实例详解new和delete 内存管理

本文详细解析了C++中String类的构造、析构过程及内存分配与释放机制,通过实例代码展示了new/delete与malloc/free的区别,并揭示了在进行字符串操作时如何避免内存泄露的问题。

上一篇文章简单介绍了malloc/free和new/delete的区别,当然,我建议大家多用new/delete;

下面上一段代码让大家更好的来理解这个应用

///////////////String.h///////////////////////////////////////////////////////////
#ifndef STRING_H_
#define STRING_H_
#include <iostream>
using namespace std;
class String
{
private:
	char * str; //存储数据
	int len; //字符串长度
public:
	String(const char * s); //构造函数
	String(); // 默认构造函数
	~String(); // 析构函数
	friend ostream & operator<<(ostream & os,const String& st);
};

#endif


 

////String.cpp
#include "stdafx.h"
#include <string>
#include <iostream>
#include "String.h"

using namespace std;


String::String(const char *s)
{
	len=strlen(s);
	str=new char[len+1];
	strcpy(str,s);
}
String::String()
{
	len=0;
	str=new char[len+1];
	str[0]='"0';
}

String::~String()
{

	cout<<"将完成删除操作;"<<str<<'"n'<<endl;
	delete []str;
	cout<<str<<endl;
}
ostream &operator <<(ostream &os,const String  &st)
{
	os<<st.str;
	return os;
}
// testString.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include "String.h"

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	String temp("wangchenglin 我爱你");
	cout<<temp<<endl;
	//system("PAUSE");
	return 0;
}

 

程序运行的结果:

很诡异的是,我delete操作,为什么依然还是垃圾呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值