Register__ 2022-04-30 00:52 采纳率: 89.5%
浏览 30
已结题

C++多线程在对象构造以及传参方面的问题


class P{
    int m;
public :
    P(const int& x) : m(x){
        printf("P(const int& x) x = %d this_thread = %X pos = %X\n",x,this_thread::get_id(),this);
    }
    P(const P& p): m(p.m){
        printf("P(const P& p) x = %d this_thread = %X pos = %X\n",p.m,this_thread::get_id(),this);
    }
    ~P(){
        printf("~P() this_thread = %X pos = %X\n",this_thread::get_id(),this);
    }
};

void func(const P& pp){
    printf("chile th id  = %X pp's pos = %X\n",this_thread::get_id(),&pp);
}
int main(){

    cout<<"-->main begin<--\n";
    cout<<"main id = "<<this_thread::get_id()<<endl;
    P pp(1);
    thread p1(func,pp);
    p1.detach();
    cout<<"-->mian end<--\n";
    return 0;
}

-->main begin<--
main id = 1
P(const int& x) x = 1 this_thread = 1 pos = 62FE08
P(const P& p) x = 1 this_thread = 1 pos = 62FDA0
P(const P& p) x = 1 this_thread = 1 pos = DE1A38
~P() this_thread = 1 pos = 62FDA0
chile th id  = 2 pp's pos = DE1A38
~P() this_thread = 2 pos = DE1A38
-->mian end<--
~P() this_thread = 1 pos = 62FE08

img

这里对象 怎么 创建的 , 首先pp创建了 调用了const int& 构造 , 然后 P 为什么 会在 主线程 中被 **拷贝两次 **, 这两次 为什么 拷贝 , 我觉得 首先 如果 这个 函数 如果不是线程 函数 入口的 话, 那么 这里 就应该 **出现一次 **const int& 的 构造 调用, 因为 引用 底层 也就是 指针 , 传参数 传的 是地址值(大概可以这么理解吧,意思就是 同一份东西), **那么这里 多出来的 两个拷贝 是 干什么的 **, 其次 就是 最后 一个 拷贝的(0xDE1A38) 对象 在 主线程中创建,子线程 中被销毁(这里我觉得没问题,主线还没消失,内存还在), 然后 第二个 对象(0x62FDA0) 比 第一个先销毁(在 主线程 中)不理解, 第一个 对象 为什么 ,主线 都结束了 , 他还能在 主线 中 被销毁 !!??

  • 写回答

2条回答 默认 最新

  • fortunely2 2022-04-30 14:59
    关注

    第一次调用P(const int&)构造函数。
    第二次、第三次,应该是在构造thread对象时,发生了拷贝构造。
    如果想避免拷贝构造,建议用这种方式:

    P pp(1);
    thread p1(std::bind(&func, ref(pp)));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月9日
  • 已采纳回答 5月1日
  • 创建了问题 4月30日

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端