本文介绍了thread_local std :: unique_ptr释放不调用析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么在中调用析构函数:
#include< iostream>
#include< thread>
#include< memory>
class base {
public:
base(){
std :: cout< base()< std :: endl;
}
virtual〜base(){
std :: cout< 〜base()<< std :: endl;
}
base(const base&)= delete;
base(base&&)= delete;
base& operator =(const base&)= delete;
base& operator =(base&&)= delete;
};
类派生final:public base {
public:
derived(){
std :: cout< derived()<< std :: endl;
}
virtual〜derived(){
std :: cout< 〜derived()<< std :: endl;
}
};
void foo(){
static thread_local std :: unique_ptr< base> ptr;
if(!ptr){
std :: cout<< new ptr:< std :: this_thread :: get_id()<< std :: endl;
ptr.reset(new derived());
} else {
std :: cout<< release ptr:< std :: this_thread :: get_id()<< std :: endl;
ptr.release(); //我期望析构函数在这里被调用?
}
}
void thread_main(){
foo();
foo();
}
int main()
{
std :: thread thread1(thread_main);
thread1.join();
return 0;
}
输出:
new ptr:140671459997440
base()
derived()
release ptr:140671459997440
我会期望:
new ptr:140671459997440
base()
derived()
release ptr:140671459997440
〜derived()
〜base()
使用 gcc 4.9.1
解决方案
使用 ptr.reset();
替换 ptr.release();
p>
Why isn't the destructor called in this code:
#include <iostream>
#include <thread>
#include <memory>
class base {
public:
base() {
std::cout << "base()" << std::endl;
}
virtual ~base() {
std::cout << "~base()" << std::endl;
}
base(const base&) = delete;
base(base&&) = delete;
base& operator=(const base&) = delete;
base& operator=(base&&) = delete;
};
class derived final : public base {
public:
derived() {
std::cout << "derived()" << std::endl;
}
virtual ~derived() {
std::cout << "~derived()" << std::endl;
}
};
void foo() {
static thread_local std::unique_ptr<base> ptr;
if (!ptr) {
std::cout << "new ptr:" << std::this_thread::get_id() << std::endl;
ptr.reset(new derived());
} else {
std::cout << "release ptr:" << std::this_thread::get_id() << std::endl;
ptr.release(); // I would expect the destructor to be called here?!
}
}
void thread_main() {
foo();
foo();
}
int main()
{
std::thread thread1(thread_main);
thread1.join();
return 0;
}
Output:
new ptr:140671459997440
base()
derived()
release ptr:140671459997440
I would expect:
new ptr:140671459997440
base()
derived()
release ptr:140671459997440
~derived()
~base()
Using gcc 4.9.1
解决方案
Replace ptr.release();
with ptr.reset();
.
这篇关于thread_local std :: unique_ptr释放不调用析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!