如果不主动编写拷贝构造函数和赋值函数,编译器就会以按成员拷贝的方式自动生成相应的默认函数。倘若类中含有指针成员或引用成员,那么这两个默认的函数就可能隐含错误。
假设String类有一个char *m_data的数据成员,a.m_data的内容为“hello”,b.m_data的内容也为“hello”,现在将a赋值给b,默认赋值函数的按成员拷贝意味着执行b.m_data = a.m_data。这会造成3个错误
(1)b.m_data原来持有的内存没有释放。
(2)b.m_data和a.m_data指向同一块内存,任何一方的改动会影响其他一方。
(3)在对象被析构时,m_data被delete了两次。
String a("hello");
String b("hello");
String c=a; //调用默认拷贝构造函数,风格不好,宜改写为String c(a);
c=b; //赋值函数
示例:String的拷贝构造函数和赋值函数
Stirng::String(const String &other)
{
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data, other.m_data);
}
String & String::operator=(const String &other)
{
if(this != &other) 、// 有a=a的情况
{
char *temp = new char[strlen(other.m_data)+1];
strcpy(temp, other.m_data);
delete [] m_data;
m_data = temp;
}
return *this;
}
原文链接: https://www.cnblogs.com/zzj3/archive/2013/04/26/3045219.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/86076
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!