asfwa said:
I'm new to C++ and I have some basic questions.
I have written an app that does some network stuff in a worker thread. The
thread function requests something from the server, gets it and creates an
object from the server response. Does this thread terminate/stop/die as soon
as it completes its last line of code? Or do I have to do something to kill
it?
This depends on your OS and the API that you've used to create the
threads. I assume you are using windows. In that case, read the
documentation for the particular API calls you are making in the MSDN
archives, Platform SDK. As far as I remember, if a thread terminates
normally, you just have to call CloseHandle. This is the code that I
used within a wrapper class destructor - no guarantees - but seemed to
work fine (good idea to wrap your thread) - the comments are added for
your convenience:
Note:
All variables with trailing underscores are private data members of
this fictitious class:
//Destructor
MyTask::~MyTask()
{
if( taskHandle_ )
{
HANDLE handle = taskHandle_;
taskHandle_ = 0; //Invalidates taskHandle_ henceforth
threadState_ = eThreadState_TERMINATED; //Internal state - you can
ignore
DWORD exitCode;
::GetExitCodeThread( handle, &exitCode );
if( exitCode == STILL_ACTIVE)
{
::CloseHandle( handle );
::TerminateThread( handle, -1 );
}
else
{
::CloseHandle( handle );
}
}
}
I am used to coding Java so I am totally unsure of what I have to do to
"clean up" my variables/objects and free up memory etc. Should I use
"delete" for all objects I instantiate?
You are on dangerous ground. Coming from Java you have a lot to learn.
If you create objects on the heap (using operator new), you should
destroy them using operator delete. Automatic variables (variables
created on the stack) are destroyed automatically too (when the stack
unwinds). For these operator new is not used (in short - there is a
longer version). Example:
void foo()
{
int value = 0; //Will be automagically be destroyed at the end of foo
scope...
Object myObject; //... and this too.
int* pvalue = new int( value ); //calling copy-ctor for integer...,
//...needs to be destroyed explicitly at scope end or leak - for
this,
// boost::scoped_ptr is a handy idiom.
delete pvalue; //Good
//Another version using scoped_ptr...
boost::scoped_ptr<int> pvalue2( new int(value) );
//Because the scoped ptr is on the stack (or automatic), it will be
destroyed,
// and it's destructor will implicitly destroy (call delete on...)
// the wrapped ptr.
}
How do I remove primitive type variables?
See above. By primitive, I'm assuming you mean variables not created on
the heap.
Regards,
W