一个class如果包含了普通指针成员的话那就必须实现(如果是智能指针则则没有必要)特别是复制构造函数和移动构造函数不要忘记
- 构造函数,
- 析构函数,
- 拷贝构造函数,
- 移动构造函数,
- 移动赋值函数
- 拷贝复制函数
上述缺少一个都会造成内存泄漏;
=delete =default 关键字一般只会用在上述几个函数,普通函数几乎不用,
拷贝构造和拷贝赋值函数还必须检查是否是自己给自己拷贝
一个class 对象对容器的操作在没有实现移动构造函数的情况之下,就会调用拷贝构造函数实现push_back(),实现移动构造函数的情况之下,就会调用移动构造函数实现push_back(),赋值表达式也是一样;
#include<iostream>
#include<list>
using namespace std;
class A
{
private:
int a;
int *buf;
public:
A(){
a = 0;
buf = new int[100];
cout << "A" << endl;
}
~A(){
if (buf != nullptr)
{
delete[]buf;
cout << "~A" << endl;
}
}
A(const A &tmp) //= delete;
{
if(this!=&tmp)//检查自己拷贝自己
{
this->a = a;
this->buf = new int[100];
cout << "copy A" << endl;
}
}
A( A &&tmp)
{
cout << "move A" << endl;
this->a = a;
this->buf = tmp.buf;
tmp.buf = nullptr;
}
A operator=(const A &temp)// = delete;
{
this->a = a;
this->buf = new int[100];
cout << "= A" << endl;
return *this;
}
A operator=( A &&temp)
{
cout << "move = A" << endl;
this->a = a;
this->buf = temp.buf;
temp.buf = nullptr;
return std::move(*this);
}
A copyA(A&a)
{
return std::move(a);
}
};
int main()
{
list<A> list_;
for (auto a : { 1, 2, 4 })
{
cout << "-------begin------" << endl << endl;
list_.push_back(A());
}
cout << "-------1------" << endl;
list_.clear();
cout << "-------2------" << endl;
{
A a;
A b = a;
const A c;
A d = c;
}
getc(stdin);
return 1;
}
智能指针测试代码
#include<iostream>
#include<list>
#include<memory>
using namespace std;
int cnt=0;//记录C的分配析构次数
class C
{
public :
int c;
public:
C(int aa) :c(aa)
{
cnt++;
cout << "C" << endl;
}
~C()
{
cnt--;
cout << "~C" << endl;
}
C(const C&)
{
cout << "C copy" << endl;
cnt++;
}
};
int a=0;//记录B的分配析构次数
class B
{
public:
std::shared_ptr<C> buf=nullptr;
public:
B(){
buf = make_shared<C>(3);
cout << "B" << endl;
a++;
}
~B(){
if (buf != nullptr)
{
a--;
cout << "~B" << endl;
}
}
//B(const B &tmp) = delete;
//{
//
// this->buf = make_shared<C>(*tmp.buf);
// a++;
// cout << "copy B" << endl;
// //return *this;
//}
//B(B &&tmp)
//{
// cout << "move B" << endl;
// this->a = a;
// this->buf = tmp.buf;
// tmp.buf = nullptr;
//}
B operator=(const B &temp)// = delete;
{
a++;
this->buf = make_shared<C>(*temp.buf);
cout << "= B" << endl;
return *this;
}
B operator=(B &&temp)
{
cout << "move = B" << endl;
this->buf = temp.buf;
temp.buf = nullptr;
return std::move(*this);
}
};
int main()
{
list<B> list_;
for (auto a : { 1, 2, 4 })
{
cout << "-------begin------" << endl << endl;
list_.push_back(B());
}
cout << "-------1------" << endl;
list_.clear();
cout << "-------2------" << endl;
{
//B a;
//B b = a;
}
cout << "a = " << a << "cnt = " << cnt << endl;
getc(stdin);
return 1;
}