Deep Copy and Shallow Copy

If your class manages resources (like dynamically allocated arrays), it
should implement the following three things:

  1. A copy constructor
  2. An override for the = operator
  3. A destructor
    • The idea is that there are implicit definitions for each of these
    elements and it is important to handle them appropriately (and
    probably explicitly), especially when the implicit/default behavior is
    undesirable.
class MyClass {
public:
int a; double* b;
MyClass() : a(10), b(new double[20]) {}
MyClass(const MyClass& m) : b(new double[20])
{
a = m.a;
for (int i = 0; i < 20; i++)
b[i] = m.b[i];
}
virtual ~MyClass() { delete[] b; }
MyClass& operator=(const MyClass& m) {
a = m.a;
for (int i = 0; i < 20; i++)
b[i] = m.b[i];
return *this;
}
};

Simplified Version:

class MyClass {
public:
int a; double* b;
MyClass() : a(10), b(new double[20]) {}
MyClass(const MyClass& m) : b(new double[20])
{
*this = m; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
virtual ~MyClass() { delete[] b; }
MyClass& operator=(const MyClass& m) {
a = m.a;
for (int i = 0; i < 20; i++)
b[i] = m.b[i];
return *this;
}
};

A word of advice: understand how operator overloading is declared and
used (think about the [] operator of the vector template) but hold off on
overloading operators yourself except for the = operator

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值