c++STL存对象析构问题

Black8zzz 2008-01-24 05:09:46
class temp
{
public:
char *p;
temp(char *lhs)
{
//p=lhs; 在这里动态分配与静态分配好像一样的???
p=new char[strlen(lhs)+1];
strcpy(p,lhs);
}

~temp()
{
delete []p;//如果不将对象放入容器当中那结果正确,但放入容器就显示错误
//是不是放入容器中后就会将对象中的资源自动释放掉???
}
};

int main()
{
temp tmp("wkl");
temp tmp2("www");

vector<temp> vec;
vec.push_back(tmp);
vec.push_back(tmp2);

cout<<vec[0].p<<endl;
cout<<vec[1].p<<endl;

return 0;
}
...全文
144 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Black8zzz 2008-01-24
  • 打赏
  • 举报
回复
谢谢各位,非常感谢……
0黄瓜0 2008-01-24
  • 打赏
  • 举报
回复
楼主记住,如果类拥有资源(最常见的是一个指针指向动态分配的内存),那么都应该重载拷贝构造函数和赋值运行符.

stl的容器里面存储的都是对象的复本,所以要发生拷贝构造.
zhangyue02135 2008-01-24
  • 打赏
  • 举报
回复
你看看我给你改的代码就明白了:
class temp
{
public:
char *p;
temp(char *lhs)
{
p=new char[strlen(lhs)+1];
strcpy(p,lhs);
}

temp(const temp& tmp)
{
cout<<"In copy constructor!"<<endl;
this->p = new char[strlen(tmp.p)+1];
strcpy(this->p, tmp.p);
}

~temp()
{
delete []p;
}
};

int main()
{
temp tmp("a");
temp tmp2("b");
temp tmp3("c");

vector<temp> vec;
vec.push_back(tmp);
cout<<"1"<<endl;
vec.push_back(tmp2);
cout<<"2"<<endl;
vec.push_back(tmp3);
cout<<"3"<<endl;

cout<<"tmp obj in vector:"<<endl;

vector<temp>::iterator it;
it = vec.begin();
for (; it != vec.end(); it++)
{
cout<<(*it).p<<endl;
}

return 0;
}

运行结果:
In copy constructor!
1
In copy constructor!
In copy constructor!
2
In copy constructor!
In copy constructor!
In copy constructor!
3
tmp obj in vector:
a
b
c
很明白吧,在插入进vector时就是用新的temp object去覆盖前面的,所以插入多少个就调用多少次拷贝构造。具体与stl中vector的实现有关,不过已经很明显了!



Black8zzz 2008-01-24
  • 打赏
  • 举报
回复
还是有点不明白,当存入向量时就调用,而且是三次,为什么呢,拷贝到向向时两次,另一次是什么时候?
taodm 2008-01-24
  • 打赏
  • 举报
回复
在拷贝构造函数里加一个打印,你就能知道哪一行调用它了。
Black8zzz 2008-01-24
  • 打赏
  • 举报
回复
哪句调用了拷贝构造函数,求解,困扰我有些日子了
taodm 2008-01-24
  • 打赏
  • 举报
回复
兄弟,你没实现拷贝构造函数。

65,210

社区成员

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

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