这样定义拷贝构造函数会有什么问题?

we_sky2008 2009-12-15 09:05:24
#include<iostream>
#include<string.h>

using namespace std;


class base
{
public:
base(char *str_b = "base")
{
this->str_b = new char[strlen(str_b) + 1];
strcpy(this->str_b, str_b);
}
base(const base& other)
{
this->str_b = new char[strlen(other.str_b) + 1];
strcpy(str_b, other.str_b);
}

virtual ~base()
{
delete str_b;
}
void display()
{
cout<<str_b<<endl;
}
private:
char *str_b;
};


class derived : public base
{
public:
derived(){}
derived(char* str_b, char *str_d) : base(str_b)
{
this->str_d = new char[strlen(str_d) + 1];
strcpy(this->str_d, str_d);
}
derived(derived& other)// : base(other)
{ //这样写的话会有什么问题?既不在初始化表里调用基类拷贝构造函数也不在函数体内直接赋值
base::base(other);//而是像这样来初始化基类部分 理论上应该会有内存泄露
this->str_d = new char[strlen(other.str_d) + 1];
strcpy(str_d, other.str_d);
}

virtual ~derived()
{
delete str_d;
}
void display()
{
base::display();
cout<<str_d<<endl;
}
private:
char *str_d;
};


int main()
{
derived d("hello", "world"), d1(d);

return 0;
}


请看程序和程序的注释。
程序本身并没什么意义,我只是想知道如果这样做会有什么后果,
谢谢大家!
...全文
77 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
we_sky2008 2009-12-15
  • 打赏
  • 举报
回复
谢谢大家!
macrojj 2009-12-15
  • 打赏
  • 举报
回复
derived(derived& other)// : base(other)
{ //这样写的话会有什么问题?既不在初始化表里调用基类拷贝构造函数也不在函数体内直接赋值 调用的是默认构造函数
base::base(other);//而是像这样来初始化基类部分 理论上应该会有内存泄露 事实证明 你并没有初始化基类部分。这将产生临时变量。
this->str_d = new char[strlen(other.str_d) + 1];
strcpy(str_d, other.str_d);
}
苍蝇①号 2009-12-15
  • 打赏
  • 举报
回复
应该不会的,这样的代码太常见了,如果有问题的话不知道有多少服务器早就停机了
we_sky2008 2009-12-15
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 supermegaboy 的回复:]
base::base(other);这一句不是在派生类对象中创建基类对象,只不过产生了一个base的临时对象,这个临时对象在derived的复制构造函数结束的时候析构了。你的代码主要问题就在于析构的时候使用了delete而不是delete []。
[/Quote]

恩,确实应该是delete [];
但是我觉得base::base(other);这一句是在派生类对象中创建基类对象可以用d1.display();看下结果
但是此时基类部分已经通过基类的缺省构造函数构造了(并且缺省构造函数分配了动态内存),
再调用基类的拷贝构造相当于另外又开辟了另外的动态空间,而原来的还没释放

是这样吗?请大家分析一下,谢谢!
飞天御剑流 2009-12-15
  • 打赏
  • 举报
回复
base::base(other);这一句不是在派生类对象中创建基类对象,只不过产生了一个base的临时对象,这个临时对象在derived的复制构造函数结束的时候析构了。你的代码主要问题就在于析构的时候使用了delete而不是delete []。
we_sky2008 2009-12-15
  • 打赏
  • 举报
回复

应该写成delete[]这个形式

我主要是想问下面的有什么问题,谢谢!
derived(derived& other)// : base(other)
{ //这样写的话会有什么问题?既不在初始化表里调用基类拷贝构造函数也不在函数体内直接赋值
base::base(other);//而是像这样来初始化基类部分 理论上应该会有内存泄露
this->str_d = new char[strlen(other.str_d) + 1];
strcpy(str_d, other.str_d);
}
pengzhixi 2009-12-15
  • 打赏
  • 举报
回复
你不是做了深拷贝吗?另外析构函数里面用delete[]这个形式

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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