Re: problem delete class object contained thread
morz <blackrosezy@gmail.com> wrote:
classA
{
public:
thirdPartyThreadLibrary myThread;
void Run()
{
myThread.exec(); // created new thread and run on background.
}
};
void myGUIFunctionNamed_Execute()
{
classA * objectA = new classA();
objectA->Run();
delete objectA <---- here is my big problem.If i put this
line,
surely
myThread in classA deleted.auto_ptr
also cannot help.If i dont put this line,
my code is perfectly run,but of course
memory leaked.
So, ask yourself how long you would need the resource objectA. I suppose
as long as the created thread runs. If so, I would dispose the object
after having "joined" the thread, i.e. as soon as the thread dies. (That
is, if "join" is available and part of your design. C++ doesn't
specify what threads are, but the most popular thread abstraction is
possibly POSIX, and POSIX does offer "join").
However, given your design, there's likely another problem, namely that
of error handling. What do you do in case a thread cannot be launched
for whatever reason?
I want myGUIFunctionNamed_Execute()
return immediately after i called it,but i dont no how to delete
object(objectA)
inside this function.My idea is to use auto pointer
This helps nothing. The auto_ptr binds the lifetime of the object
pointed to to the life-time of the pointer itself. But what you want to
do is to extend the life-time of the object to at least the life-time
of the thread. So you *must* know or control when the thread goes down
in some way.
Possibilties:
- Dispose the object after having joined the thread within the main program
- Dispose the object as the last action of the thread within the thread
itself, making sure that you do not access it anymore.
- Dispose the object at the end of your program.
So long,
Thomas
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]