介绍
- 拷贝赋值注意事项
1.拷贝赋值也有深拷贝和浅拷贝
2.如果类中没有定义赋值运算符重载函数,编译器会提供一个 默认的赋值运算符函数
3.拷贝赋值应尽可能 复用拷贝构造 和 析构函数 代码
4.尽量避免使用 指针型成员变量、缺省拷贝构造函数、缺省拷贝赋值运算符函数 因为都只是浅拷贝
5.尽量通过 引用 或 指针 向函数传递 对象型参数,减少拷贝构造,提高效率
6.若提供了自定义 拷贝构造函数 ,那么也要提供 拷贝赋值运算符函数
- 与拷贝构造相比,拷贝赋值需要做的操作有:
1.避免自赋值
2.分配新资源
3.拷贝新内容
4.释放旧资源
5.返回自引用
源码
#include<iostream>
#include<string>
using namespace std;
class Array
{
friend ostream& operator<<(ostream& out,Array& arr);
friend istream& operator>>(istream& out, Array& arr);
public:
char& at(int index)
{
return m_array[index];
}
size_t size()
{
return m_size;
}
public:
Array& operator=(const Array&that)
{
cout << "拷贝赋值函数" << endl;
#if 0
if (&that != this)
{
char*ptemp = new char[that.m_size];
if (ptemp == nullptr)
{
cerr << "Bad Allocation" << endl;
return *this;
}
strcpy(ptemp, that.m_array);
if (m_a