stout中大量使用了c++11的特性,而c++11中move和forward大概是最神奇的特性了.

  1. 左值和右值的区别
int a = ;   // a是左值,0是右值
int b = rand(); // b是左值,rand()是右值

  直观理解:左值在等号左边,右值在等号右边

  深入理解:左值有名称,可根据左值获取其内存地址,而右值没有名称,不能根据右值获取地址。

  2. 引用叠加规则

  左值引用A&和右值引用A&& 可相互叠加

A& + A& = A&
A& + A&& = A&
A&& + A& = A&
A&& + A&& = A&&

  举例示例,void foo(T&& x)中,如果T是int&, x为左值语义,如果T是int&&, x为右值语义

 

  3. 为什么要使用std::move

  如果类X包含一个指向某资源的指针,在左值语义下,类X的赋值构造函数如下:

X::X(const X& other)
{
// ....
// 销毁资源
// 复制other的资源,并使指针指向它
// ...
}

  应用代码如下,其中,tmp被赋给a之后,便不再使用。

X tmp;
// ...经过一系列初始化...
X a = tmp;

  如上,执行过程按照时间顺序如下: 首先执行一次默认构造函数(tmp申请资源),再执行一次复制构造函数(a复制资源), 最后退出作用域时再执行一次析构函数(tmp释放资源)。既然tmp迟早要被析构掉,在执行复制构造函数的时候,a能不能将tmp的资源“偷“”过来,直接为我所用?

X::X(const X& other)
{
// 交换this和other的资源
}

  这样可以减少一次资源的创建和释放。这就是std::move所要实现的。

  

  4. std::move的实现

  std::move用于强制将左值转化为右值。其实现方式如下:

template<class T>
typename remove_reference<T>::type&&
std::move(T&& a) noexcept
{
typedef typename remove_reference<T>::type&& RvalRef;
return static_cast<RvalRef>(a);
}

  当a为int左值(右值)时,根据引用叠加原理,T为int&, remove_reference<T> = int, std::move返回类型为int&&,即右值引用

  

  5. std::move的使用

#include <utility>
#include <iostream>
#include <string>
#include <vector> void foo(const std::string& n)
{
std::cout << "lvalue" << std::endl;
} void foo(std::string&& n)
{
std::cout << "rvalue" << std::endl;
} void bar()
{
foo("hello"); // rvalue
std::string a = "world";
foo(a); // lvalue
foo(std::move(a)); // rvalue
} int main()
{
std::vector<std::string> a = {"hello", "world"};
std::vector<std::string> b; b.push_back("hello");
b.push_back(std::move(a[])); std::cout << "bsize: " << b.size() << std::endl;
for (std::string& x: b)
std::cout << x << std::endl;
bar();
return ;
}

  6. 为什么要使用std::forward

  首先看下面这段代码:

#include <utility>
#include <iostream> void bar(const int& x)
{
std::cout << "lvalue" << std::endl;
} void bar(int&& x)
{
std::cout << "rvalue" << std::endl;
} template <typename T>
void foo(T&& x)
{
bar(x);
bar(std::forward<T>(x));
} int main()
{
int x = ;
foo(x);
foo();
return ;
}

  执行foo(10):首先进入函数foo, 执行bar(x), 输出"lvalue"。这里有点不合常理,10明明是一个右值,为什么这里输出"lvalue"呢?这是因为10只是作为一个foo的右值参数,但是在foo函数内部,x却是一个有名字的变量,因此10是bar(x)的左值参数。但是我们想延续10的左值语义,怎么办呢?std::forward就派上了用场。

  总而言之,std::forward的目的就是保持std::move的语意。

  7. std::forwar的实现

template<typename T, typename Arg>
shared_ptr<T> factory(Arg&& arg)
{
return shared_ptr<T>(new T(std::forward<Arg>(arg)));
}
template<class S>
S&& forward(typename remove_reference<S>::type& a) noexcept
{
return static_cast<S&&>(a);
}
X x;
factory<A>(x);

  如果factory的输入参数是一个左值 => Arg = X& => std::forward<Arg> = X&, 这种情况下,std::forward<Arg>(arg)仍然是左值。

  相反,如果factory输入参数是一个右值 => Arg = X => std::forward<Arg> = X, 这种情况下,std::forward<Arg>(arg)是一个右值。

  

  8. std::forward的使用

  直接上码,如果前面都懂了,相信这段代码的输出结果也能猜个八九不离十了。  

#include <utility>
#include <iostream> void overloaded(const int& x)
{
std::cout << "[lvalue]" << std::endl;
} void overloaded(int&& x)
{
std::cout << "[rvalue]" << std::endl;
} template <class T> void fn(T&& x)
{
overloaded(x);
overloaded(std::forward<T>(x));
} int main()
{
int i = ;
overloaded(std::forward<int>(i));
overloaded(std::forward<int&>(i));
overloaded(std::forward<int&&>(i)); fn(i);
fn(std::move(i)); return ;
}

stout代码分析之十:c++11之move和forward的更多相关文章

  1. WebShell代码分析溯源(十)

    WebShell代码分析溯源(十) 一.一句话变形马样本 <?php $e = $_REQUEST['e'];register_shutdown_function($e, $_REQUEST[' ...

  2. stout代码分析之零

    最近在使用mesos做高可用设计,在编译的过程中注意到mesos依赖stout,一个仅仅含有头文件的c++基础库.stout代码简洁,设计优雅,值得一读. stout从内容上可细分为以下几块: Pri ...

  3. stout代码分析之九:c++11容器新特性

    stout大量使用了c++11的一些新特性,使用这些特性有利于简化我们的代码,增加代码可读性.以下将对一些容器的新特性做一个总结.主要两方面: 容器的初始化,c++11中再也不用手动insert或者p ...

  4. stout代码分析之十一:hashmap和multihashmap

    hashmap是std::unordered_map的子类,前者对后者的接口做了进一步封装. hashmap的移动构造函数: hashmap(std::map<Key, Value>&am ...

  5. stout代码分析之八:cache类

    stout中实现了LRU cache.cache的成员如下: public: typedef std::list<Key> list; typedef std::tr1::unordere ...

  6. stout代码分析之七:Result类

    Result类似于Option和Try类的组合,内部有三种状态 enum State { SOME, NONE, ERROR }; SOME表示Result对象有值 NONE表示Result对象值为空 ...

  7. stout代码分析之六:Stopwatch

    在进行性能测试时,经常需要计算某个函数执行的时长.stout中的Stopwatch类可实现纳秒精度的计时. Stopwatch内部使用timespec记录开始和技术时间.   timeval和time ...

  8. stout代码分析之五:UUID类

    UUID全称通用唯一识别码,被广泛应用于分布式系统中,让所有的元素具有唯一的标识. stout中UUID类继承自boost::uuids::uuid.api如下: random, 产生一个UUID对象 ...

  9. stout代码分析之一:Duration类

    Duration类用于表示时间长度,可精确到纳秒. 代码实现在duration.hpp中,测试代码:duration_tests.cpp 相关api如下: parse, 将字符串转化成Duration ...

随机推荐

  1. gitignore 文件生效办法

    .gitignore 可以添加一些不加入git版本控制的文件 比如一些测试文件.因人而异的配置信息等等 .gitignore 文件展示如下 /.idea/target//.classpath /.pr ...

  2. Python3 集合

    1.集合的表示 集合是一个无序不重复的元素序列 创建空集合 set() 2.集合的运算 a={1,2,3} b={2,3,4} print(a-b) #a中包含b中不包含 print(a|b) #a中 ...

  3. IntelliJ IDEA 2018 for MAC安装及破解

    ---------------------说在前面-------------------------- IntelliJ IDEA 2018 版本为2018.1.4 教程按照下载安装sdk.破解两部分 ...

  4. lintcode-191-乘积最大子序列

    191-乘积最大子序列 找出一个序列中乘积最大的连续子序列(至少包含一个数). 样例 比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6. 标签 子数组 领英 动态规划 ...

  5. OSG学习:矩阵变换节点示例

    #include<osgViewer\Viewer> #include<osg\Node> #include<osg\Geode> #include<osg\ ...

  6. 原生javascript自定义input[type=checkbox]效果

    2018年6月27日  更新 能用css3,就不用js 用纯css3实现样式重写 <!DOCTYPE html> <html lang="en"> < ...

  7. Ubuntu下找不到php5,phpize等可执行程序的解决办法

    Ubuntu下找不到php5,phpize等可执行程序的解决办法 [日期:2010-10-25] 来源:eetag.com  作者:eetag [字体:大 中 小]     环境:Linux Ubun ...

  8. 【Docker 命令】- exec命令

    docker exec :在运行的容器中执行命令 语法 docker exec [OPTIONS] CONTAINER COMMAND [ARG...] OPTIONS说明: -d:分离模式: 在后台 ...

  9. 文件“bin\Debug\WindowsFormsApplication2.exe”正由另一进程使用,因此该进程无法访问该文件。

    http://zhidao.baidu.com/question/221394579.html?qbl=relate_question_2&word=%BE%AF%B8%E6%094%09%C ...

  10. CURL & Fetch

    CURL & Fetch https://kigiri.github.io/fetch/ https://stackoverflow.com/questions/31039629/conver ...