请问这样会不会造成内存泄漏

casualplayer 2009-04-21 09:18:05
像下面这样写,怎样释放main方法中的new分配?


class Cstring
{
private:
char* ps;
public:
//构造函数
Cstring(const char* s = "")
{
int max = strlen(s) + 1;
ps = new char[max];
strcpy_s(ps, max, s);
}
//复制构造函数
Cstring(const Cstring* cs)
{
int max = strlen(cs->ps) + 1;
ps = new char[max];
strcpy_s(ps, max, cs->ps);
}
//析构函数
~Cstring()
{
delete [] ps;
}
void show() const
{
printf("%s\n", ps);
}
};

int main(void)
{
Cstring asdf(new Cstring("asdf"));
asdf.show();

return 0;
}
...全文
88 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wanglc08 2009-04-21
  • 打赏
  • 举报
回复

#include <iostream>
//

using namespace std;
class Cstring
{
private:
char* ps;
public:
//构造函数
Cstring(const char* s = "")
{
int max = strlen(s) + 1;
ps = new char[max];
strcpy_s(ps, max, s);
}
//复制构造函数
Cstring(const Cstring* cs)
{
int max = strlen(cs->ps) + 1;
ps = new char[max];
strcpy_s(ps, max, cs->ps);
}
//析构函数
~Cstring()
{
delete [] ps;
}
void show() const
{
printf("%s\n", ps);
}
};

int main(void)
{
Cstring* a=new Cstring("asdf");
Cstring asdf(a);
asdf.show();
delete a;
return 0;
}
T技术沙龙 2009-04-21
  • 打赏
  • 举报
回复
学习,不过我一般用黄金内存管理我的内存,主要还是为了防止编程的时候造成的内存泄露,已经好几次解决这个问题了,推荐楼主可以用一下
operatingtuzi 2009-04-21
  • 打赏
  • 举报
回复
1楼这样写可以吗? 不是cstring *a?

楼主是调用了拷贝构造函数吧,不过这个拷贝构造函数的形式没怎么见过。。。一般会用引用吧

创建临时对象就分配了一段空间,深拷贝的时候又分配了。深拷贝的那个在出栈的时候会自动调用析构函数释放吧,不过临时对象的。。不知道怎么释放了。。
mengde007 2009-04-21
  • 打赏
  • 举报
回复

#include <iostream>
//

using namespace std;




class Cstring
{
private:
char* ps;
public:
//构造函数
Cstring(const char* s = "")
{
int max = strlen(s) + 1;
ps = new char[max];
strcpy_s(ps, max, s);
}
//复制构造函数
Cstring(const Cstring* cs)
{
int max = strlen(cs->ps) + 1;
ps = new char[max];
strcpy_s(ps, max, cs->ps);
}
//析构函数
~Cstring()
{
delete [] ps;
}
void show() const
{
printf("%s\n", ps);
}
};

int main(void)
{
Cstring* a=new Cstring("asdf");
Cstring asdf(a);
asdf.show();
delete a;
return 0;
}


mengde007 2009-04-21
  • 打赏
  • 举报
回复
Cstring a=new Cstring("asdf");
delete a;

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧