如何在线程之间传递指向类对象的指针,并在主线程完成执行后使其保留?

发布于 2024-11-02 00:59:47 字数 217 浏览 1 评论 0原文

这是我遇到的问题:

主线程创建类对象(mybaseclass* local = new childclass;),这些对象本质上是知道它们应该做什么的命令。然后,它通过套接字将指向类对象的指针传递给分叉线程,然后主线程完成该对象的处理并返回等待其他输入。然后,分叉线程从队列中读取指针,但当主线程完成时,指针指向的类对象已被自动删除。主线程执行完毕后,如何使类对象持久存在?

谢谢! 杰夫

Here's the problem that I'm having:

The main thread creates class objects (mybaseclass* local = new childclass;) which are essentially commands that know what they are suppose to do. It then passes a pointer to the class object to a forked thread over a socket and then the main thread is done with the object and returns waiting for some other input. The forked thread then reads the pointer from the queue, but the class object that the pointer was pointing to has already been automatically deleted when the main thread completed. How do I get the class object to persist once the main thread is done executing?

Thanks!
Jeff

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许仙没带伞 2024-11-09 00:59:47

当线程完成时,使用 new 关键字在堆上分配的对象不会自动删除。如果您确信它会被自动删除,则其他地方可能存在错误。否则,指针仍应指向有效对象。

Objects allocated on the heap with the new keyword aren't automatically deleted when a thread completes. If you're positive that it's being automatically deleted, you may have a bug elsewhere. Otherwise, the pointer should still point to a valid object.

吹泡泡o 2024-11-09 00:59:47

在主线程中,使用 new 在免费存储上创建对象:

mybaseclass* local = new childclass;

...确保不要使用智能指针,因为当对象超出范围时,智能指针将销毁该对象。通过您使用的任何方式将指针传递给您的工作线程,然后当您的工作线程完成使用它时,将其删除:

mybaseclass* thread_local = SomehowGetTheObject();
// MAGIC HAPPENS...
delete thread_local;

此外,如果您将基指针传递给派生类,请确保您的基类有一个 虚拟析构函数。

In your main thread, create your object on the free store, using new:

mybaseclass* local = new childclass;

...being sure not to use a smart pointer, as the smart pointer will destroy the object when it falls out of scope. Pass the pointer to your worker thread via whatever means you are using, then when your worker thread is done with it, delete it:

mybaseclass* thread_local = SomehowGetTheObject();
// MAGIC HAPPENS...
delete thread_local;

Also, if you are passing around base pointers to derived classes, be sure your base class has a virtual destructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文