【发布时间】:2011-11-05 21:41:49
【问题描述】:
我想了解这段代码的行为。
class Foo
{
public:
Foo();
~Foo();
void run();
int* get();
private:
int *a;
};
Foo::Foo()
{
a=NULL;
}
void Foo::run()
{
if ( a==NULL)
a = new int[30000];
}
int* Foo::get()
{
return a;
}
Foo::~Foo()
{
cout << "destructor called" << endl;
if ( a!=NULL)
delete a;
}
int main()
{
Foo *a = new Foo();
boost::thread Foothread( &Foo::run, a);
// Some very long computation that sometimes access
int *b = a->get();
cout << *b << endl;
//Foothread.join();
//delete a;
//Foothread.join();
return 0;
}
此代码导致 120000 字节的内存泄漏,因为变量 a 没有被破坏,所以当我明确删除它时,泄漏消失了,一切都应该没问题。
现在如果我不是动态分配a,而是使用静态分配,析构函数会被多次调用!!!
int main()
{
Foo a;
boost::thread Foothread( &Foo::run, a);
// Some very long computation that sometimes access "a"
Foothread.join();
int *b = a.get();
cout << *b << endl;
return 0;
}
输出是 调用析构函数,a 为 0 现在 a 为 0 调用析构函数,a 为 0 现在 a 为 0 调用析构函数,a 为 0 现在 a 为 0 调用析构函数,a 为 0 现在 a 为 0 调用析构函数,a 为 0 现在 a 为 0 调用析构函数,a 为 0 现在 a 为 0 调用析构函数,a 为 0x75e300 现在 a 为 0 分段错误
析构函数被调用了N次!!
现在我想知道如何使用 boost::thread 安全地分配和解除分配类成员变量和对象,以及为什么线程析构函数不显式处理类析构函数。
有人可以给我一个提示吗? boost::smart_ptr 应该帮助我吗?我必须用 malloc 分配内存(因为我需要使用一些旧的 C API),我怎样才能做到线程安全?
【问题讨论】:
标签: multithreading boost memory-leaks destructor