开发者

How do I pass a pointer to a class object between threads and have it persist after the main thread finishes executing?

Here's the problem that I'm having:

The main thread creates class obje开发者_如何学运维cts (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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜