C :如何使用thread_local声明指针变量
C++: How to use thread_local to declare a pointer variable?
我尝试声明thread_local指针变量,然后在一个线程中指向一个新对象。
thread_local static A* s_a = nullptr;
似乎是在线程销毁时没有释放新对象的记忆。我还尝试使用unique_ptr,但仍在内存泄漏。我正在使用VS2015。
这是代码。在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以正确的方式声明指针变量?
谢谢。
标准对线程的支持是极为基础。
Boost的跨平台支持当然是优越的:
// for thread_specific_ptr
#include <boost/thread/tss.hpp>
// define a deleter for As
void destroy_a(A* ptr) noexcept
{
delete ptr;
}
// define the thread_specific pointer with a deleter
boost::thread_specific_ptr<A> s_a { &destroy_a };
static void test(const std::string& name)
{
// create the object in a manner compatible with the deleter
if(!s_a.get())
{
s_a.reset(new A(name));
}
}
thread_local static std::unique_ptr<A> s_a;
有效。任务管理器中的内存不是正确的。我使用VLD演示内存,未检测到内存泄漏。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别