我试图声明thread_local指针变量,然后指向一个线程中的新对象。C++:如何使用thread_local声明一个指针变量?
thread_local static A* s_a = nullptr;
看到新对象的内存没有在线程销毁时被释放。我也尝试使用unique_ptr,但仍然存在内存泄漏。我使用VS 2015
这里是代码。在return 0
处添加一个断点,检查进程的内存,你会看到内存增加很多。
#include "stdafx.h"
#include <iostream>
#include <thread>
class A
{
public:
A(const std::string& name) : name_(name) { std::cout << (name_ + "::A").c_str() << std::endl; }
~A() { std::cout << (name_ + "::~A").c_str() << std::endl; }
const std::string& name(){ return name_; }
private:
std::string name_;
};
thread_local static std::unique_ptr<A> s_a;
//thread_local static A* s_a = nullptr;
static void test(const std::string& name)
{
//A a(name);
if(!s_a)
s_a.reset(new A(name));
//s_a = new A(name);
}
int main()
{
for (size_t i = 0; i < 10000; i++)
{
{
std::thread t0(test, "t0");
std::thread t1(test, "t1");
t0.join();
t1.join();
}
}
return 0;
}
我的问题是如何使用thread_local以正确的方式声明指针变量?
谢谢。
我想它是在一个线程单一实例,是什么把它删除的时机?为什么使用unique_ptr还是内存泄漏? – ldlchina
相关:https://stackoverflow.com/questions/17668729/memory-leak-in-gcc-4-8-1-when-using-thread-local。 [gcc错误报告](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57914)。应该在4.8.2中固定。 – AMA
'static thread_local unique_ptr'应该可以工作。你怎么知道有泄漏? – rustyx