1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C++ 深拷贝和浅拷贝std::move移动构造函数 移动赋值函数

C++ 深拷贝和浅拷贝std::move移动构造函数 移动赋值函数

时间:2023-07-17 01:15:15

相关推荐

C++ 深拷贝和浅拷贝std::move移动构造函数 移动赋值函数

一个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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。