std::thread函数传参拷贝次数

c++11的thread库大大方便了开发,但是目前网络上少有深入分析的资料和使用例程。特别是在线程函数传参这一块,一般止步于使用std::ref传引用。

这次写服务器遇到个BUG,线程函数参数是智能指针,传递方式是pass by value, 设想的是引用计数+1,但是实质上是引用计数+2。一个在于内部tuple存储是用的拷贝构造,然后函数调用的时候也是用的拷贝构造。但是实质上不仅仅这2次拷贝构造。写了断代码测试了下。

#include <iostream>
#include <memory>
#include <thread>

using namespace std;

class MyClass
{
public:
    MyClass(){};
    ~MyClass(){ cout << "destruct" << endl; };
    MyClass(const MyClass& my){ cout << "copy" << endl; }



};

void test(MyClass my)
{
    while (true)
    {

    }
}

int main()
{
    MyClass my;
    thread t(test, my);
    t.detach();
    while (1)
    {
    }
    return 0;
}

输出如下

进行了5次拷贝构造,3次析构。这是thread隐藏的细节部分。具体是怎样的,等我把源码读懂了再来写。标准库的源码风格看着真的头大。

 经过测试,只会调用拷贝构造,不会调用赋值操作符。

posted @ 2017-03-08 20:40  超三界  阅读(1767)  评论(0编辑  收藏  举报