我正在一个类中编写一个linux守护进程,它是一个App类的智能指针:
应用程序.hpp
class App
{
public:
App(void)
{
this->ptrDaemon = std::make_unique<Daemon>();
this->ptrDaemon->ptrApp = this;
}
~App(void) = default;
// Members
public:
std::unique_ptr<Daemon> ptrDaemon = nullptr; // This is constructed in the constructor
};
守护进程.hpp
class Daemon
{
~Daemon() = default;
App *ptrApp = nullptr; // This pointer is assigned to the app instance in the App constructor
bool daemonise()
{
pid_t pid{};
pid = fork();
if (pid < 0)
{
return false;
}
// Exit father
if (pid > 0)
{
this->ptrApp->~App(); // This works, but is it a good practice?
std::exit(EXIT_SUCCESS);
}
// More code
}
}
在这种情况下,我需要提前退出父进程,所以如果我使用 std::exit(0)
智能指针将不会被释放。为了避免这种情况,我使用了其他对象的析构函数。
这是一个好习惯吗(在我看来很难看)?我可以使用其他任何解决方案吗?
提前致谢!
答案 0 :(得分:4)
这是一个好习惯吗(在我看来很难看)?
不,在成员函数中调用析构函数通常不是一个好习惯。
<块引用>我可以使用其他解决方案吗?
当然。以下是一些:
App
实例可能不是唯一没有被销毁的对象。std::exit
提前终止,而是像平常一样从 main
返回。这是确保所有破坏都得到妥善处理的唯一方法。