我很好奇为什么像下面附加的一个简单的 C++ 程序在 std::thread 中处理 work1 对象时多次调用它的析构函数。为什么它多次调用析构函数。
class work1 {
public:
work1(int x_) : x(x_) {
++count;
std::cout<<"\n[WORKER1] Ctor : "<<count<<std::endl;
}
~work1() {
std::cout<<"\n[WORKER1] Dtor : "<<count<<std::endl;
}
void operator() () {
for(int i =0; i < x; ++i) {
std::cout<<"[WORKER1] Printing this :: "<<i<<std::endl;
}
}
private:
int x;
static int count;
};
int main()
{
int local_main=5;
std::thread t((work1(local_main)));
t.join();
std::cout<<"\n[MAIN] From main thread..."<<std::endl;
return 0;
}
上面的代码产生以下输出:
[WORKER1] Ctor : 1
[WORKER1] Dtor : 1
[WORKER1] Dtor : 1
[WORKER1] Printing this :: 0
[WORKER1] Printing this :: 1
[WORKER1] Printing this :: 2
[WORKER1] Printing this :: 3
[WORKER1] Printing this :: 4
[WORKER1] Dtor : 1
[MAIN] From main thread...
std::thread
通过调用复制构造函数来复制参数。实现复制构造函数以观察副本:
class work1 {
public:
work1(int x_) : x(x_) {
++count;
std::cout << __PRETTY_FUNCTION__ << ' ' << count << '\n';
}
work1(work1 const& other)
: x(other.x)
{
++count;
std::cout << __PRETTY_FUNCTION__ << ' ' << count << '\n';
}
work1& operator=(work1 const& other)
{
x = other.x;
std::cout << __PRETTY_FUNCTION__ << ' ' << count << '\n';
return *this;
}
~work1() {
--count;
std::cout << __PRETTY_FUNCTION__ << ' ' << count << '\n';
}
void operator() () {
for(int i =0; i < x; ++i) {
std::cout<<"[WORKER1] Printing this :: "<<i<<std::endl;
}
}
private:
int x;
static int count;
};
int work1::count;
int main() {
int local_main=5;
std::thread t((work1(local_main)));
t.join();
}
输出:
work1::work1(int) 1
work1::work1(const work1&) 2
work1::work1(const work1&) 3
work1::~work1() 2
work1::~work1() 1
[WORKER1] Printing this :: 0
[WORKER1] Printing this :: 1
[WORKER1] Printing this :: 2
[WORKER1] Printing this :: 3
[WORKER1] Printing this :: 4
work1::~work1() 0
如果您想避免复制传递对功能对象的引用,则该线程使用std::ref
:
int main() {
work1 w{5};
std::thread t(std::ref(w));
t.join();
}
输出:
work1::work1(int) 1
[WORKER1] Printing this :: 0
[WORKER1] Printing this :: 1
[WORKER1] Printing this :: 2
[WORKER1] Printing this :: 3
[WORKER1] Printing this :: 4
work1::~work1() 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句