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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。