【发布时间】:2019-07-20 08:46:49
【问题描述】:
我不知道为什么即使我调用了对象的成员函数,即使它仍然在它的范围内,仍然调用了析构函数。 一个简单的例子如下:
#include<thread>
#include<iostream>
class Obj1
{
private:
public:
~Obj1();
void testFunc();
};
Obj1::~Obj1()
{
std::cout<<"destory\n";
}
void Obj1::testFunc(){
std::cout<<"testfun\n";
}
#include "Obj1.hpp"
#include <thread>
#include <chrono>
int main()
{
using namespace std::chrono_literals;
Obj1 obj1 = Obj1();
for(int i=0;i<100;i++){
std::thread th = std::thread(&Obj1::testFunc,obj1);
std::this_thread::sleep_for(1s);
std::cout<<"we wait\n";
}
}
当我尝试运行它时,我可以看到输出:
destory
testfun
destory
we wait
terminate called without an active exception
Aborted (core dumped)
我想知道为什么每次线程结束时都会销毁obj1? p.s. 1s延迟的原因是因为这是在实时系统中使用的,主循环频率较低,任务将在下一个循环之前完成。
【问题讨论】:
-
仅供参考。这是矫枉过正:
Obj1 obj1 = Obj1();应该只是Obj1 obj1;。其次,线程参数是按值的(所以在你的情况下,复制)。如果要引用同一个对象,请使用 ref-wrapper。我会使用 obj1 的地址。 -
你为什么要睡1s?让线程完成工作?不好的做法。你也不叫 th.join() 或 th.detach();
-
您正在复制对象但您不知道它,因为您没有记录对 Big Five 的所有调用(仅是析构函数)。见stackoverflow.com/questions/56799469/…,这里是what happens when you fix the logging
-
@WhozCraig std::ref(obj1) ???
-
@HAOLEE for member fn ptrs,它将采用 obj 地址或绑定设置。前者在我下面的回答中。
标签: c++ multithreading oop c++11 c++14