深拷贝和浅拷贝
- 没有提供任何构造函数的时候,系统默认生成构造和析构函数。
- 当需要使用拷贝构造函数是,系统默认生成拷贝构造函数,是内存拷贝。
class seqStack {
private:
int* _pstack;
int _size;
int _top;
public:
seqStack(int size) {
_size = size;
_pstack = new int[size];
_top = -1;
}
~seqStack() {
delete[]_pstack;
_pstack = nullptr;
}
};
int main() {
seqStack s1(10);
seqStack s2 = s1; // 默认拷贝构造,属于内存拷贝,是一种浅拷贝。
//析构顺序与构造顺序相反,先析构s2,delete了栈空间,s1析构再次释放栈空间会报错。
}
- 对象如果占用外部资源,浅拷贝会出现问题,应转为深拷贝。
- 深拷贝:不仅做内存拷贝,还做外部资源的内容拷贝。
class seqStack {
// private:
// int* _pstack;
// int _size;
// int _top;
public:
seqStack(int size) {
_size = size;
_pstack = new int[size];
_top = -1;
}
~seqStack() {
delete[]_pstack;
_pstack = nullptr;
}
//自定义拷贝构造函数
seqStack(const seqStack &seq) {
_pstack = new int[seq._size];
for (int i = 0; i <= seq._top; i++) {
_pstack[i] = seq._pstack[i];
}
_size = seq._size;
_top = seq._top;
}
//重载等号运算符
//如果需要支持连续赋值,重载等号运算符函数应为seqStack类型,返回*this
void operator=(const seqStack& seq) {
if (this == &seq) //防止自赋值
return;
delete[] _pstack;
_pstack = new int[seq._size];
for (int i = 0; i <= seq._top; i++) {
_pstack[i] = seq._pstack[i];
}
_size = seq._size;
_top = seq._top;
}
};
int main() {
seqStack s1(10);
seqStack s2(s1); //调用拷贝构造函数
seqStack s3 = s1; //调用拷贝构造函数
//默认的等号运算符是内存拷贝,浅拷贝
s3 = s1;// //已经不是初始化阶段了,重载等号运算符
}
标签:11,seqStack,int,pstack,拷贝,构造函数,size
From: https://www.cnblogs.com/sio2zyh/p/17967087