美文网首页
右值引用:移动语义和完美转发

右值引用:移动语义和完美转发

作者: ColdWave | 来源:发表于2018-10-17 21:22 被阅读0次

右值引用:移动语义和完美转发

指针成员与拷贝构造

#include <iostream>
using namespace std;

class HasPtrMem {
public:
    HasPtrMem(): d(new int(0)) {}
    ~HasPtrMem() { delete d; }
    int * d;
};

int main() {
    HasPtrMem a;
    HasPtrMem b(a);
    cout << *a.d << endl;   // 0
    cout << *b.d << endl;   // 0
}   // 析构:运行时错误,多次在同一位置调用delete
  • 浅拷贝(shollow copy)

在未声明拷贝构造函数时,编译器也会为类生成一个浅拷贝构造函数。

解决浅拷贝问题的方法是用户自定义拷贝函数,进行“深拷贝”(deep copy)。

#include <iostream>
using namespace std;

class HasPtrMem {
public:
    HasPtrMem(): d(new int(0)) {}
    HasPtrMem(const HasPtrMem & h):
        d(new int(*h.d)) {} // 拷贝构造函数,从堆中分配内存,并用*h.d初始化
    ~HasPtrMem() { delete d; }
    int * d;
};

int main() {
    HasPtrMem a;
    HasPtrMem b(a);
    cout << *a.d << endl;   // 0
    cout << *b.d << endl;   // 0
}   // 正常析构析构

左值,右值和右值引用

在C++11中所有的值必属于左值(lvalue)、右值(rvalue)两者之一,右值又可以细分为纯右值(prvalue, Pure RValue)、将亡值(xvalue, eXpiring Value)。

在C++11中可以取地址的、有名字的就是左值,反之,不能取地址的、没有名字的就是右值(将亡值或纯右值)。

a = b+c;

// a 左值, &a 合法
// b+c 是右值, &(b+c) 非法

纯右值

  • 非引用返回的函数返回的临时变量值
  • 1+3 产生的临时变量
  • 2, 'c', true
  • 类型转换函数的返回值
  • lambda 表达式

将亡值

将亡值则是 C++11 新增的跟右值引用相关的表达式,这样表达式通常是将要被移动对象.

  • 返回右值引用 T&& 的函数返回值
  • std::move 的返回值
  • 转换为 T&& 的类型转换函数的返回值

右值引用就是对一个右值进行引用的类型.

通常情况下,右值不具有名字,我们只能通过引用的方式找到它.

T&& a = RetureRvalue();
/*
 * a 是右值引用
 * RetureRvalue 返回一个临时变量
 * a 这个右值引用 引用 RetureRvalue 返回的临时变量
*/

右值引用和左值引用都是属于引用类型。无论是声明一个左值引用还是右值引用,都必须立即进行初始化。而其原因可以理解为是引用类型本身自己并不拥有所绑定对象的内存,只是该对象的一个别名。左值引用是具名变量值的别名,而右值引用则是不具名(匿名)变量的别名。

通常情况下,右值引用不能绑定到任何左值上.

int c;
int &&d = c; // error, 左值引用不能绑定到左值上

C++98 左值引用是否可以绑定到右值上?

T& e = RetureRvalue();          // error
const T& f = RetureRvalue();    // ok

在 C++98 中,常量左值引用就是个"万能"的引用类型.可以接受非常量左值、常量左值、右值对其进行初始化.而且使用右值对其初始化的时候,常量左值引用还可以向右值引用一样将右值的生命周期延长.不过相比于右值引用所引用的右值,常量左值引用所引用的右值在它的"余生"中只能是只读的.相对的,非常量左值引用只能接受非常量左值对其初始化.

在 C++98 中使用 常量左值引用 来减少临时对象的开销:

#include <iostream>
using namespace std;

struct Copyable {
    Copyable() {}
    Copyable(const Copyable &o) {
        cout << "Copied" << endl;
    }
};

Copyable ReturnRvalue() { return Copyable(); }
void AcceptVal(Copyable) {}
void AcceptRef(const Copyable & cp) {}//Copyable c = std::move(cp);}
void AcceptRRef(int && i) {i+=3; cout << (char)i << endl;}

int main() {
    cout << "Pass by value: " << endl;
    AcceptVal(ReturnRvalue()); // 临时值被拷贝传入
    cout << "Pass by reference: " << endl;
    AcceptRef(ReturnRvalue()); // 临时值被作为引用传递
    AcceptRRef('c'); // 临时值被作为引用传递
}

常量右值引用

const T&& crvalueref = RetureRvalue();

右值引用就是为了移动语义,而移动语义需要右值是可以被修改的,那么常量右值引用在移动语义中就没有用处;二来如果要引用右值且让右值不可以更改,常量左值引用就够了。

引用类型 非常量左值 常量左值 非常量右值 常量右值 注记
非常量左值引用 Y N N N
常量左值引用 Y Y Y Y 全部类型,可用于拷贝语义
非常量右值引用 N N Y N 用于移动语义、完美转发
常量右值引用 N N Y Y 暂无用途
#include <type_traits>

std::cout << is_lvalue_reference<string &&>::value;
std::cout << is_rvalue_reference<string &&>::value;

移动语义

#include <iostream>
using namespace std;

class A {
public:
    int x;
    A(int x) : x(x)
    {
        cout << "Constructor" << endl;
    }
    A(A& a) : x(a.x)
    {
        cout << "Copy Constructor" << endl;
    }
    A& operator=(A& a)
    {
        x = a.x;
        cout << "Copy Assignment operator" << endl;
        return *this;
    }
    A(A&& a) : x(a.x)
    {
        cout << "Move Constructor" << endl;
    }
    A& operator=(A&& a)
    {
        x = a.x;
        cout << "Move Assignment operator" << endl;
        return *this;
    }
};

A GetA()
{
    return A(1);
}

A&& MoveA()
{
    return A(1);
}

int main()
{
    cout << "-------------------------1-------------------------" << endl;
    A a(1);
    cout << "-------------------------2-------------------------" << endl;
    A b = a;
    cout << "-------------------------3-------------------------" << endl;
    A c(a);
    cout << "-------------------------4-------------------------" << endl;
    b = a;
    cout << "-------------------------5-------------------------" << endl;
    A d = A(1);
    cout << "-------------------------6-------------------------" << endl;
    A e = std::move(a);
    cout << "-------------------------7-------------------------" << endl;
    A f = GetA();
    cout << "-------------------------8-------------------------" << endl;
    A&& g = MoveA();
    cout << "-------------------------9-------------------------" << endl;
    d = A(1);
}
/*
-------------------------1-------------------------
Constructor
-------------------------2-------------------------
Copy Constructor
-------------------------3-------------------------
Copy Constructor
-------------------------4-------------------------
Copy Assignment operator
-------------------------5-------------------------
Constructor
-------------------------6-------------------------
Move Constructor
-------------------------7-------------------------
Constructor
-------------------------8-------------------------
Constructor
-------------------------9-------------------------
Constructor
Move Assignment operator
*/
#include <iostream>
using namespace std;

class HasPtrMem {
public:
    HasPtrMem(): d(new int(0)) {
        cout << "Construct: " << ++n_cstr << endl;
    }
    HasPtrMem(const HasPtrMem & h): d(new int(*h.d)) {
        cout << "Copy construct: " << ++n_cptr << endl;
    }
    ~HasPtrMem() {
        delete d;
        cout << "Destruct: " << ++n_dstr << endl;
    }
    int * d;
    static int n_cstr;
    static int n_dstr;
    static int n_cptr;
};

int HasPtrMem::n_cstr = 0;
int HasPtrMem::n_dstr = 0;
int HasPtrMem::n_cptr = 0;

HasPtrMem GetTemp() { return HasPtrMem(); }

int main() {
    HasPtrMem a = GetTemp();
}
/*
 * 程序输出:
 * Construct: 1
 * Copy construct: 1
 * Destruct: 1
 * Copy construct: 2
 * Destruct: 2
 * Destruct: 3
*/
/*
 * 在新的版本的编译器程序输出:
 * Construct: 1
 * Destruct: 1
*/

本示例想说明一个问题,拷贝构造的调用,尤其是深拷贝构造的调用,会进行内存的memcpy,消耗大量资源。

C++11 的移动语义(move semantics):

不会进行拷贝构造,只是将临时变量“偷来”。

#include <iostream>
using namespace std;

class HasPtrMem {
public:
    HasPtrMem(): d(new int(3)) {
        cout << "Construct: " << ++n_cstr << endl;
    }
    HasPtrMem(const HasPtrMem& h) : d(new int(*h.d)) {
        cout << "Copy construct: " << ++n_cptr << endl;
    }
    HasPtrMem(HasPtrMem && h): d(h.d) { // 移动构造函数
        h.d = nullptr;                  // 将临时值的指针成员置空
        cout << "Move construct: " << ++n_mvtr << endl;
    }
    ~HasPtrMem() {
        delete d;
        cout << "Destruct: " << ++n_dstr << endl;
    }
    int * d;
    static int n_cstr;
    static int n_dstr;
    static int n_cptr;
    static int n_mvtr;
};

int HasPtrMem::n_cstr = 0;
int HasPtrMem::n_dstr = 0;
int HasPtrMem::n_cptr = 0;
int HasPtrMem::n_mvtr = 0;

const HasPtrMem GetTemp() {
    HasPtrMem h;
    cout << "Resource from " <<  __func__ << ": " << hex << h.d << endl;
    return h;
}

int main() {
    const HasPtrMem && a = GetTemp();
    cout << "Resource from " <<  __func__ << ": " << hex << a.d << endl;
    // hex << a.d ===> hex(a.d)
}
/*
    Construct: 1
    Resource from GetTemp: 0x907ab0
    Resource from main: 0x907ab0
    Destruct: 1
*/
// 移动构造并没有被调用,该示例无法说明任何问题.

std::move 强制转换为右值

std::move 将一个左值强制转换为右值引用,继而我们通过右值使用该值,以用于移动语义。

// 等价于:
static_cast<T&&>(lvalue);

被强制转化的左值,其生命周期并没有随着左右值的变化而改变。

#include <iostream>

class Moveable {
public:
    Moveable(): i (new int(3)) {
        std::cout << "Moveable" << std::endl;
    }
    ~Moveable() { delete i; }
    Moveable(const Moveable & m) : i(new int(*m.i)) {}
    Moveable(Moveable && m) : i (m.i) {
        m.i = nullptr;
    }

    int *i;
};

int main()
{
    Moveable a;
    Moveable c(std::move(a));   // a 为左值,强制转换为右值
    std::cout << *(a.i) << std::endl; // 在 std::move(a) 时, a.i 就被设置为了 nullptr, 故这里运行时错误

    return 0;
}

相关文章

网友评论

      本文标题:右值引用:移动语义和完美转发

      本文链接:https://www.haomeiwen.com/subject/sbkdzftx.html