DeepAnchor 2020-10-28 10:55 采纳率: 0%
浏览 145

C++多线程传递类对象调用2次拷贝构造函数?


#include <iostream>
#include <thread>

class Ta
{
public:
    int &ta_s;

    Ta(int taS) : ta_s(taS)
    {
        std::cout<<"构造函数"<< this <<std::endl;
    }

    virtual ~Ta()
    {
        std::cout<<"析构函数"<< this << std::endl;
    }

    Ta(const Ta &ta):ta_s(ta.ta_s)
    {
        std::cout<<"拷贝构函数"<< this << std::endl;
    }

    void operator()()
    {
        std::cout<<"haha"<< this <<std::endl;
    }
};

int main()
{
    int a = 0;
    Ta ta(a);
    std::thread th(ta);
//    th.detach();
    th.join();

    return 0;
}

结果如下所示:

构造函数0x7ffeebff2578
拷贝构造函数0x7ffeebff24e0
拷贝构造函数0x7fd524400648
析构函数0x7ffeebff24e0
haha0x7fd524400648
析构函数0x7fd524400648
析构函数0x7ffeebff2578

请问,拷贝构造调用了两次吗?我已知晓的就一次,请赐教!

  • 写回答

1条回答 默认 最新

  • wlj1234 2020-10-28 15:52
    关注

    Ta ta(a);调用了一次构造函数,std::thread th(ta);又调用了一次构造函数
    std::thread在构造时,建立tuple对象,tuple对象内部_Tuple_val进行了Ta对象的拷贝。你可以跟踪看一下!

    评论

报告相同问题?