c++ 之 std move 原理实现与用法总结_std move

v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
//调用移动构造函数,掏空str,掏空后,最好不要使用str
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \"" << v[0]
                                     << "\", \"" << v[1] << "\"\n";

}


输出:



After copy, str is “Hello”
After move, str is “”
The contents of the vector are “Hello”, “Hello”


#### **std::move 的函数原型定义**



template
typename remove_reference::type&& move(T&& t)
{
return static_cast<typename remove_reference::type&&>(t);


 


#### **原型定义中的原理实现:**


 首先,函数参数T&&是一个指向模板类型参数的右值引用,通过引用折叠,此参数可以与任何类型的实参匹配(可以传递左值或右值,这是std::move主要使用的两种场景)。关于引用折叠如下:


      公式一)X& &、X&& &、X& &&都折叠成X&,用于处理左值



string s(“hello”);
std::move(s) => std::move(string& &&) => 折叠后 std::move(string& )
此时:T的类型为string&
typename remove_reference::type为string 
整个std::move被实例化如下
string&& move(string& t) //t为左值,移动后不能在使用t
{
    //通过static_cast将string&强制转换为string&&
    return static_cast<string&&>(t); 
}


  
       公式二)X&& &&折叠成X&&,用于处理右值



std::move(string(“hello”)) => std::move(string&&)
//此时:T的类型为string 
//     remove_reference::type为string 
//整个std::move被实例如下
string&& move(string&& t) //t为右值
{
    return static_cast<string&&>(t);  //返回一个右值引用
}


  
 简单来说,右值经过T&&传递类型保持不变还是右值,而左值经过T&&变为普通的左值引用.


②对于static\_cast<>的使用注意:任何具有明确定义的类型转换,只要不包含底层const,都可以使用static\_cast。



double d = 1;
void* p = &d;
double dp = static_cast<double> p; //正确
 
const char *cp = “hello”;
char q = static_cast<char>(cp); //错误:static不能去掉const性质
static_cast(cp); //正确


  
 ③对于remove\_reference是通过类模板的部分特例化进行实现的,其实现代码如下



//原始的,最通用的版本
template struct remove_reference{
    typedef T type;  //定义T的类型别名为type
};
 
//部分版本特例化,将用于左值引用和右值引用
template struct remove_reference<T&> //左值引用
{ typedef T type; }
 
template struct remove_reference<T&&> //右值引用
{ typedef T type; }   
  
//举例如下,下列定义的a、b、c三个变量都是int类型
int i;
remove_refrence<decltype(42)>::type a;             //使用原版本,
remove_refrence<decltype(i)>::type  b;             //左值引用特例版本
remove_refrence<decltype(std::move(i))>::type  b;  //右值引用特例版本


#### **总结:**


std::move实现,首先,通过右值引用传递模板实现,利用引用折叠原理将右值经过T&&传递类型保持不变还是右值,而左值经过T&&变为普通的左值引用,以保证模板可以传递任意实参,且保持类型不变。然后我们通过static\_cast<>进行强制类型转换返回T&&右值引用,而static\_cast<T>之所以能使用类型转换,是通过remove\_refrence<T>::type模板移除T&&,T&的引用,获取具体类型T。


####  参考链接:


https://blog.youkuaiyun.com/fengbingchun/article/details/52558914 


https://blog.youkuaiyun.com/cpriluke/article/details/79462388 


<https://blog.youkuaiyun.com/swartz_lubel/article/details/59620868>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值