C++11 右值引用与move语义

1. 右值引用

1.1 右值
右值就是指在下一个分号后(更准确的说是在包含右值的完整表达式的最后)销毁的临时对象。
对于C++ 11,编译器会依据参数是左值还是右值在复制构造函数和move构造函数间进行选择。怎样区分呢?
The distinguishing criterion is: if it has a name, then it is an lvalue. Otherwise, it is an rvalue.
以右值引用为参数的构造函数像这样:
string(string&& that)   // string&& is an rvalue reference to a string
    {
        data = that.data;
        that.data = nullptr;
    }

1.2 copy-and-swap
与(Create-Temporary-and-Swap)不同。
When to implement a class that manages a resource, remember the rule of three:
If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

这个原则被成为The Big Three或者Rule of Three。Destructor和copy constructor其实都比较好写,但想写一个完美的assignment operator overloading则是一件略有挑战性的事情。这种情况下,copy-and-swap idiom(以下简称为CASI)就应运而生了。
    CASI的运行过程大抵是这样的:首先使用copy constructor创建一个数据的local copy,然后使用一个swap function来把老的数据替换成这个local copy中的新数据。函数结束时,local copy自动销毁,我们就只剩下了新的数据。

1.3 赋值构造函数

对move语义来说,下面代码成为move-and-swap惯用法:   

string& operator=(string that)    // note the missing reference    
{
    std::swap(data, that.data);
    return *this;
}
    为什么没出现引用符呢?

    复制赋值操作符和转移赋值操作符可以合并到一起,形成一个以值为参数的统一赋值操作符:

X& X::operator=(const X&);   // copy assignment operator
X& X::operator=(X&&);         // move assignment operator
合并为:
X& X::operator=(X source)    // unified assignment operator
{
    swap(source); 
    return *this;
}
    注意到我们是直接对参数that传值,所以that会像其他任何对象一样被初始化,那么that是怎样被初始化的呢?对于C++ 98,答案是拷贝构造函数,也就是copy and swap的惯用法。对于C++ 11,编译器会依据参数是左值还是右值在复制构造函数和转移构造函数间进行选择。


2. move语义

2.1 将左值转化为右值

    void func(string&& str_right) { ... }

    string a("something");

    func( a ); // error, a 是左值

    func( std::move(a) ); // ok.

注意即便std::move(a)是右值,但它自己并不生成一个临时对象。

例如:

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

2.2 对模板来说:

    template<typename T>
    void foo(T&&);

T&&不是一个右值引用,而是一个通用引用类型,它也以指向左值。

   

Ref:

http://blog.csdn.net/seemuch/article/details/8461687

http://www.cnblogs.com/tingshuo/archive/2013/01/22/2871328.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值