我继承了一个多线程的旧代码,我认为这没有正确地破坏对象。
class A
{
private:
TCCState *b; // TCCState is struct from third party library
public:
static A func1();
~A();
};
std::unique_ptr<A> A::func1()
{
std::unique_ptr<A> res(new A());
int ret = gen_tcc_context(res); // gen_tcc_context is library function
return res; // this res is used as std::unique_ptr<A> temp(std::move(A::func1())); and then properly destroyed
}
A::~A()
{
if (b != nullptr){// Is this necessary? If yes, should I used a lock_guard for this code?
tcc_delete(b);// tcc_delete is a library function. This raises an exception - Assertion failed: ("Invalid file descriptor. File possibly closed by a different thread",0)
}
}
看起来析构函数中的代码片段正在尝试关闭已经关闭的内容。析构函数中的代码片段真的必要吗?如果是,使用锁卫是否安全?
答案 0 :(得分:1)
当对象准备好销毁时,这意味着只有当前线程在使用它。如果不是这样,则该对象的生命周期管理无效。因此,底线析构函数不需要同步。
主题外:
如果正确定义了指针,则根本不需要析构函数:
class TCCState_deleter {
public:
void operator()(TCCState *b) {
tcc_delete(b);
}
};
class A
{
private:
std::unique_ptr<TCCState, TCCState_deleter> b;
public:
static A func1();
};