本文介绍了g ++ __thread =非平凡的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用__thread修饰符作为g ++中C ++ 11的thread_local的替代。不幸的是,我的本地线程变量没有简单的构造函数(它必须设置一个整数组件的值)。
我想要使用这种构造:

  __ thread MyVariable * var; 

__thread MyVariable * MyClass :: var = nullptr;

每次我想要获取var的访问权限时,我都会检查它是否已分配:

  if(var == nullptr)
var = new MyVariable(42);



但是我不知道,如何以这种方式自由分配内存。

解决方案

__ thread 存储说明符无法处理带有不平凡构造函数和析构函数的对象。 >

对于具有不平凡构造函数和析构函数的对象,您可能喜欢使用 boost :: thread_specfic_ptr<> 。当线程在相应的线程特定对象上终止 boost :: thread_specfic_ptr<> 调用 delete


I'd like to use __thread modifier, as a substitution for thread_local from C++11, in g++. Unfortunately my local thread variable doesn't have trivial constructor (it has to set the value of one integer components).I think about using this kind of construction:

__thread MyVariable *var;

__thread MyVariable* MyClass::var = nullptr;

End every time I'd like to get an acces to var I check if it was allocated:

if(var == nullptr)
   var = new MyVariable(42);

But I have no idea, how to free allocated in this way memory.

解决方案

__thread storage specifier can not handle objects with non-trivial constructors and destructors.

For objects with non-trivial constructors and destructors you may like to use boost::thread_specfic_ptr<>. When a thread terminates boost::thread_specfic_ptr<> invokes delete on the corresponding thread-specific object.

这篇关于g ++ __thread =非平凡的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:31