C++ 深拷贝、赋值拷贝
编程环境:VS2017
语言:c++
实现功能:
/****************************************************
1.可以对内置数据类型以及自定义数据类型的数据进行存储
2.将数组中的数据存储到堆区
3.构造函数中可以传入数组的容量
4.提供对应的深拷贝以及operator=
5.提供尾插法以及尾删除法
6.提供下标操作
7.获取数组的元素个数和数组的容量
*******************************************************/
普通的拷贝构造函数只会将内存中值进行拷贝,而地址却是共用的,当一个对象修改成员 变量,另一个对象则会跟着被修改,当一个对象被内存被释放,而另外一个对象还在使用该内存,则会造成内存泄漏,为解决这一问题,则需要在拷贝时重新申请内存去存放变量,这就使用到了深拷贝。
1.类
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
template<class T>
class Array
{
public:
Array(int );
~Array();
Array(const Array&arr);
Array & operator = (const Array&arr);
void append(T value);
void remove();
T operator[](int index);
int getLenght()const
{
return m_lenght;
}
int getCount()const
{
return m_content;
}
private:
T *m_array;
int m_lenght ;
int m_content = 0;
};
template<class T>
Array<T>::Array(int content)
{
this->m_content = content;
this->m_lenght = 0;
m_array = new T[this->m_content];
memset(this->m_array, 0, this->m_content);
}
template<class T>
Array<T>::~Array()
{
if (this->m_array != nullptr)
{
delete[] this->m_array;
this->m_array = nullptr;
}
}
2.深拷贝
template<class T>
Array<T>::Array(const Array&arr)
{
this->m_content = arr.m_content;
this->m_lenght = arr.m_lenght;
this->m_array = new T[this->m_content];
memset(this->m_array, 0, this->m_content);
for (int i = 0; i < this->m_lenght; i++)
{
this->m_array[i] = arr.m_array[i];
}
}
3.拷贝构造```javascript
template<class T>
Array<T>& Array<T>::operator=(const Array<T>&arr)
{
if (this == &arr)
{
cout << "自己赋值自己" << endl;
return *this;
}
else
{
if (this->m_array != nullptr)
{
delete[] this->m_array;
this->m_array = nullptr;
this->m_content = 0;
this->m_lenght = 0;
}
this->m_content = arr.m_content;
this->m_lenght = arr.m_lenght;
this->m_array = new T[this->m_content];
memset(this->m_array, 0, this->m_content);
for (int i = 0; i < this->m_lenght; i++)
{
this->m_array[i] = arr.m_array[i];
}
}
return *this;
}
4.插入元素、删除元素、访问数组
template<class T>
inline void Array<T>::append(T value)
{
this->m_array[this->m_lenght++] = value;
}
template<class T>
inline void Array<T>::remove()
{
this->m_lenght;
this->m_array[this->m_lenght--] = 0;
}
template<class T>
inline T Array<T>::operator[](int index)
{
return this->m_array[index];
}