如何在线程之间传递指向类对象的指针,并在主线程完成执行后使其保留?
这是我遇到的问题:
主线程创建类对象(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当线程完成时,使用 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.
在主线程中,使用
new
在免费存储上创建对象:mybaseclass* local = new childclass;
...确保不要使用智能指针,因为当对象超出范围时,智能指针将销毁该对象。通过您使用的任何方式将指针传递给您的工作线程,然后当您的工作线程完成使用它时,将其删除:
此外,如果您将基指针传递给派生类,请确保您的基类有一个
虚拟析构函数。
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:
Also, if you are passing around base pointers to derived classes, be sure your base class has a
virtual
destructor.