C++11 std::ref和std::cref 简介

解释

std::ref 用于包装按引用传递的值。 
std::cref 用于包装按const引用传递的值。

#include 
#include 
#include 

using namespace std;

class A
{
public:
    mutable int m_i;
    //类型转换构造函数, 可以把一个int转换为一个类A对象
    A(int a) :m_i(a) { cout << "A::A(int a)拷贝构造函数执行" << this <<                                 
            std::this_thread::get_id() << endl; }
    A(const A& a) :m_i(a.m_i) { cout << "A::A(const A)拷贝构造函数执行" << this << 
            std::this_thread::get_id() << endl; }
    ~A() { cout << "A::~A()析构函数执行" << this << std::this_thread::get_id() << endl; }
};

void myPrint(const A &myBuf)
{
    myBuf.m_i = 99;
    cout << "myPrint的参数地址:" << &myBuf << std::this_thread::get_id() << endl;
}

int main()
{
    A obj(10);
    std::thread mytobj(myPrint, obj);
    mytobj.join();
    //mytobj.detach();
    std::cout << obj << endl;  //1)结果是10


 std::thread mytobj2(myPrint, std::ref(obj)); //强加上std::ref标志, 告诉编译器,必须用引
                                              //用的方式传递参数
    mytobj2.join();
    std::cout << obj << endl;  //2)结果是99

}

结果分析:

1)运行时侯, 虽然myPrint()中的函数是按照引用传递的, 但是通过窗口输出会知道, 还是会调用A类的拷贝函数,这个估计是编译器为了安全, 自己强加的,不能修改

2)结果会变成在myprint中修改 的值。此时通过窗口输出, 可以看到, 是没有进行A类的拷贝构造函数,只有A obj(10)时候,调用了一个A类的构造函数,做到了真正的按照引用传递, 不会在被拷贝一份。

 

https://blog.csdn.net/lmb1612977696/article/details/81543802 的例子:


void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: n1[" << n1 << "]    n2[" << n2 << "]    n3[" << n3 << "]" << std::endl;
    ++n1; // 增加存储于函数对象的 n1 副本
    ++n2; // 增加 main() 的 n2
    //++n3; // 编译错误
    std::cout << "In function end: n1[" << n1 << "]     n2[" << n2 << "]     n3[" << n3 << "]" << std::endl;
}

int main()
{
    int n1 = 1, n2 = 1, n3 = 1;
    std::cout << "Before function: n1[" << n1 << "]     n2[" << n2 << "]     n3[" << n3 << "]" << std::endl;
    std::function bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
    bound_f();
    std::cout << "After function: n1[" << n1 << "]     n2[" << n2 << "]     n3[" << n3 << "]" << std::endl;
}

运行结果:

Before function: n1[1]     n2[1]     n3[1]
In function: n1[1]    n2[1]    n3[1]
In function end: n1[2]     n2[2]     n3[1]
After function: n1[1]     n2[2]     n3[1]

分析
n1是值传递,函数内部的修改对外面没有影响。 
n2是引用传递,函数内部的修改影响外面。 
n3是const引用传递,函数内部不能修改。

 

你可能感兴趣的:(STL)