【发布时间】:2018-12-08 01:33:48
【问题描述】:
我继承了我认为没有正确销毁对象的多线程遗留代码。
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)
}
}
看起来析构函数中的代码片段试图关闭已经关闭的东西。析构函数中的代码片段真的有必要吗?如果是,使用 lock-guard 安全吗?
【问题讨论】:
-
在实际代码中,类是否遵循the rules of three, five or zero?
-
这段代码无法编译,因为
func1()在类声明中被声明为返回A对象,但在其定义中被声明为返回std::unique_ptr<A>。 -
我在这段代码中看不到任何不能正确释放东西的东西。只分配了 1 个
A对象,并且只被销毁一次,并且在被销毁时删除了它的 tcc 资源。A对象在几个unique_ptr对象周围移动的事实并没有改变这一点。A对象在最终的unique_ptr被破坏之前不会被破坏。但是,这与多线程有什么关系?此代码中没有线程。 -
如果您定义自己的删除器,您可以将
TCCState放入std::unique_ptr<TCCState, TCCStateDeleter>。
标签: c++ c++11 destructor