移动语义
1.几个基本概念的理解
(1)可以取地址的是左值,不能取地址的就是右值,右值可能存在寄存器,也可能存在于栈上(短暂存在栈)上
(2)右值包括:临时对象、匿名对象、字面值常量
(3)const 左值引用可以绑定到左值与右值上面,称为万能引用。正因如此,也就无法区分传进来的参数是左值还是右值。
?| 1 2 |
const int &ref = a;//const左值引用可以绑定到左值
const int &ref1 = 10;//const左值引用可以绑定到右值
|
(4)右值引用:只能绑定到右值不能绑定到左值
2.移动构造函数
注意:
移动函数(移动构造函数和移动赋值运算符函数)优先于复制函数(拷贝构造函数和赋值运算符函数)的执行;具有移动语义的函数(移动构造函数和移动赋值运算符函数)优先于具有复制控制语义函数(拷贝构造函数和赋值运算符函数)的执行
?| 1 2 3 4 5 6 |
string(string &&rhs)
: _pstr(rhs._pstr)
{
cout << "string(string &&)" << endl;
rhs._pstr = nullptr;
}
|
3.移动赋值函数
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 |
string &operator=(string &&rhs)
{
cout << "string &operator=(string &&)" << endl;
if(this != &rhs)//1、自移动
{
delete [] _pstr;//2、释放左操作数
_pstr = nullptr;
_pstr = rhs._pstr;//3、浅拷贝
rhs._pstr = nullptr;
}
return *this;//4、返回*this
}
|
4.std::move函数
std::move:
原理:将左值转换为右值,在内部其实上是做了一个强制转换,static_cast<t &&>(lvaule)。将左值转换为右值后,左值就不能直接使用了,如果还想继续使用,必须重新赋值。std::move()作用于内置类型没有任何作用,内置类型本身是左值还是右值,经过std::move()后不会改变。
5.面试题,关于实现string
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
class string
{
public:
//(当传递右值的时候)具有移动语义的函数优先于具有复制控制语义的函数
//移动构造函数(只针对右值)
string(string &&rhs)
: _pstr(rhs._pstr)
{
cout << "string(string &&)" << endl;
rhs._pstr = nullptr;
}
//移动赋值运算符函数(传入右值)
string &operator=(string &&rhs)
{
cout << "string &operator=(string &&)" << endl;
if(this!=&rhs){ //不能自复制
delete [] _pstr;//释放左操作数
_pstr = nullptr;
_pstr=rhs._pstr;//转移右操作的资源
rhs._pstr=nullptr;//释放右值
}
return *this;
}
private:
char* _pstr;
};
|
资源管理和智能指针
一、c语言中的问题
c语言在对资源管理的时候,比如文件指针,由于分支较多,或者由于写代码的人与维护的人不一致,导致分支没有写的那么完善,从而导致文件指针没有释放,所以可以使用c++的方式管理文件指针。。。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class safefile
{
public:
//在构造的时候托管资源(fp)
safefile(file *fp)
: _fp(fp)
{
cout << "safefile(file *)" << endl;
if(nullptr==fp)
{
cout << "nullptr == _fp " << endl;
}
}
//提供若干访问资源的方法
void write(const string &msg)
{
fwrite(msg.c_str(),1,msg.size(),_fp); //调用c语言的函数往_fp输入数据
}
//在销毁(析构)时候释放资源(fp)
~safefile()
{
cout << "~safefile()" << endl;
if(_fp)
{
fclose(_fp);
cout << "fclose(_fp)" << endl;
}
}
private:
file *_fp;
};
void test()
{
string s1 = "hello,world\n";
safefile sf(fopen("text.txt","a+"));
sf.write(s1);
}
|

二、c++的解决办法(raii技术)
1)概念:资源管理 raii 技术,利用对象的生命周期管理程序资源(包括内存、文件句柄、锁等)的技术,因为对象在离开作用域的时候,会自动调用析构函数
2)关键:要保证资源的释放顺序与获取顺序严格相反。。正好是析构函数与构造函数的作用
3)raii常见特征
1、在构造时初始化资源,或者托管资源。
2、析构时释放资源。
3、一般不允许复制或者赋值(值语义-对象语义)
4、提供若干访问资源的方法。
4)区分:值语义:可以进行复制与赋值。
5)对象语义:不能进行复制与赋值,一般使用两种方法达到要求:
(1)、将拷贝构造函数和赋值运算符函数设置为私有的就 ok 。
(2)、将拷贝构造函数和赋值运算符函数使用=delete.
6)raii技术代码
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
template <typename t>
class raii
{
public:
//通过构造函数托管资源
raii(t *data)
: _data(data)
{
std::cout<< "raii(t *)" << std::endl;
}
//访问资源的方法
t *operator->()
{
return _data;
}
t &operator*()
{
return *_data;
}
t *get()const
{
return _data;
}
void reset(t *data)
{
if(_data)
{
delete _data;
_data = nullptr;
}
_data = data;
}
//不能赋值和复制
raii(const raii&rhs) = delete;
raii&operator=(const raii&rhs)=delete;
//通过析构函数释放资源
~raii()
{
cout << "~raii()" << endl;
if(_data)
{
delete _data;
_data = nullptr;
}
}
private:
t *_data;
};
void test3()
{
//这里没给出point类的实现方式
raii<point> ppt(new point(1,2));
cout<<"ppt = ";
ppt->print();
cout<<endl;
}
|
三、四种智能指针
raii的对象ppt就有智能指针的雏形。
1、auto_ptr.cc
最简单的智能指针,使用上存在缺陷,所以被弃用。。。(c++17已经将其删除了)

2、unique_ptr
比auto_ptr安全多了,明确表明是独享所有权的智能指针,所以不能进行复制与赋值。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
unique_ptr<int> up(new int(10));
cout<<"*up="<<*up<<endl; //打印10
cout<<"up.get() = "<<up.get()<<endl; //获取托管的指针的值,也就是10的地址
cout << endl << endl;
/* unique_ptr<int> up2(up);//error,独享资源的所有权,不能进行复制 */
unique_ptr<int> up4(std::move(up)); //通过移动语义转移up的所有权
cout<<"*up="<<*up4<<endl;
cout<<"up.get() = "<<up4.get()<<endl;
unique_ptr<point> up5(new point(3,4));//通过移动语义转移up的所有权
vector<unique_ptr<point>> numbers;
numbers.push_back(unique_ptr<point>(new point(1,2)));
numbers.push_back(std::move(up5));
|
3、shared_ptr
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
shared_ptr<int> sp(new int(10));
cout << "*sp = " << *sp << endl; //打印10
cout << "sp.get() = " << sp.get() << endl; //地址
cout << "sp.use_count() = " << sp.use_count() << endl; //引用次数为1
cout<<endl<<endl;
//提前结束栈对象
{
shared_ptr<int> sp2(sp);//共享所有权,使用浅拷贝
cout << "*sp = " << *sp << endl;
cout << "sp.get() = " << sp.get() << endl;
cout << "sp.use_count() = " << sp.use_count() << endl;
cout << "*sp2 = " << *sp2 << endl;
cout << "sp2.get() = " << sp2.get() << endl; //地址都一样
cout << "sp2.use_count() = " << sp2.use_count() << endl; //引用次数加1,变为2了
}
cout << "sp.use_count() = " << sp.use_count() << endl; //又变为1了
cout << endl << endl;
shared_ptr<point> sp4(new point(3.4));//通过移动语义转移sp的所有权
vector<shared_ptr<point>> numbers;
numbers.push_back(shared_ptr<point> (new point(1,2)));
numbers.push_back(sp4);
numbers[0]->print();
numbers[1]->print();
|
3.1、循环引用
该智能指针在使用的时候,会使得引用计数增加,从而会出现循环引用的问题,两个shared_ptr智能指针互指,导致引用计数增加,不能靠对象的销毁使得引用计数变为0,从而导致内存泄漏。。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class child;
class parent
{
public:
parent()
{
cout << "parent()" << endl;
}
~parent()
{
cout << "~parent()" << endl;
}
shared_ptr<child> pparent;
};
class child
{
public:
child()
{
cout << "child()" << endl;
}
~child()
{
cout << "~child()" << endl;
}
shared_ptr<parent> pchild;
};
void test()
{
//循环引用可能导致内存泄漏
shared_ptr<parent> parentptr(new parent());
shared_ptr<child> childptr(new child());
cout << "parentptr.use_count() = " << parentptr.use_count() << endl;
cout << "childptr.use_count() = " << childptr.use_count() << endl;
cout << endl << endl;
parentptr->pparent = childptr;//sp = sp
childptr->pchild = parentptr;
cout << "parentptr.use_count() = " << parentptr.use_count() << endl;
cout << "childptr.use_count() = " << childptr.use_count() << endl;
}
|
1.解决循环引用的办法是使得其中一个改为weak_ptr,不会增加引用计数,这样可以使用对象的销毁而打破引用计数减为0的问题。。
2.修改: shared_ptr pchild;改为 weak_ptr pchild;即可解决循环引用的问题。。
?| 1 2 |
parentptr->pparent = childptr;//sp = sp
childptr->pchild = parentptr;//wp = sp,weak_ptr不会导致引用计数加1
|
4、weak_ptr
与shared_ptr相比,称为弱引用的智能指针,shared_ptr是强引用的智能指针。weak_ptr不会导致引用计数增加,但是它不能直接获取资源,必须通过lock函数从wp提升为sp,从而判断共享的资源是否已经销毁
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
weak_ptr<point> wp
{
shared_ptr<point> sp(new point(1,2));
wp = sp;
cout << "wp.use_count = " << wp.use_count() << endl;
cout << "sp.use_count = " << sp.use_count() << endl;
cout<<"wp.expired = "<<wp.expired()<<endl;//此方法等同于use_count()==0?
//等于0表示false,空间还存在
//不等0表示true,空间已经不存在了
//expired = use_count
shared_ptr<point> sp2 = wp.lock();//判断共享的资源是否已经销毁的方式就是从wp提升为sp
if(sp2)
{
cout << "提升成功" << endl;
}
else
{
cout << "提升失败" << endl;
}
}
|
四、为智能指针定制删除器
1)很多时候我们都用new来申请空间,用delete来释放。库中实现的各种智能指针,默认也都是用delete来释放空间,但是若我们采用malloc申请的空间或是用fopen打开的文件,这时我们的智能指针就无法来处理,因此我们需要为智能指针定制删除器,提供一个可以自由选择析构的接口,这样,我们的智能指针就可以处理不同形式开辟的空间以及可以管理文件指针。
2)自定义智能指针的方式有两种:
(1)函数指针
(2)仿函数(函数对象)
函数指针的形式:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
template<class t>
void free(t* p)
{
if (p)
free(p);
}
template<class t>
void del(t* p)
{
if (p)
delete p;
}
void fclose(file* pf)
{
if (pf)
fclose(pf);
}
//定义函数指针的类型
typedef void(*dp)(void*);
template<class t>
class sharedptr
{
public:
sharedptr(t* ptr = null ,dp dp=del)
:_ptr(ptr)
, _pcount(null)
, _dp(dp)
{
if (_ptr != null)
{
_pcount = new int(1);
}
}
private:
void release()
{
if (_ptr&&0==--getref())
{
//delete _ptr;
_dp(_ptr);
delete _pcount;
}
}
int& getref()
{
return *_pcount;
}
private:
t* _ptr;
int* _pcount;
dp _dp;
};
|
仿函数(函数对象)
关于删除器的使用

五、智能指针的误用
1、同一个裸指针被不同的智能指针托管,导致被析构两次。
1.1、直接使用

1.2、间接使用

2、还是裸指针被智能指针托管形式,但是比较隐蔽。。。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
class point
: public std::enable_shared_from_this<point>
{
public:
point(int ix = 0, int iy = 0)
: _ix(ix)
, _iy(iy)
{
cout << "point(int = 0, int = 0)" << endl;
}
void print() const
{
cout << "(" <<_ix
<< "," << _iy
<< ")" << endl;
}
/* point *addpoint(point *pt) */
shared_ptr<point> addpoint(point *pt)
{
_ix += pt->_ix;
_iy += pt->_iy;
//this指针是一个裸指针
/* return shared_ptr<point>(this); */
return shared_from_this();
}
~point()
{
cout << "~point()" << endl;
}
private:
int _ix;
int _iy;
};
void test3()
{
shared_ptr<point> sp1(new point(1, 2));
cout << "sp1 = ";
sp1->print();
cout << endl;
shared_ptr<point> sp2(new point(3, 4));
cout << "sp2 = ";
sp2->print();
cout << endl;
shared_ptr<point> sp3(sp1->addpoint(sp2.get()));
cout << "sp3 = ";
sp3->print();
}
|
总结
到此这篇关于c++学习之移动语义与智能指针的文章就介绍到这了,更多相关c++移动语义与智能指针内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_43679037/article/details/117260903








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。