I noticed something strange. I expect a segfault to be produced running the following code, but it isn't.
void DeadlineTimeOut(const boost::system::error_code& pErrorCode, boost::thread* pThread)
{
std::cout << "Error code: #" << pErrorCode.value()
<<开发者_开发知识库 " Message: " << pErrorCode.message() << std::endl;
std::cout << "Thread Address = "
<< pThread << std::endl; // "sth. like 0x33aabc0"
pThread->interrupt();
pThread->join();
delete pThread;
delete pThread;
std::cout << "Stopped execution thread #"
<< pThread->get_id() << std::endl; // "{Not-any-thread}"
}
So, why is the double delete possible? And also calling a member? I'm a little confused at the moment.
Deleting a pointer twice is undefined behaviour. There's no guarantee of a segfault. You might get one if you're lucky; you might not. The code might pass all your testing and then blow up in your customer's face at the worst possible moment. See the C++ FAQ.
The same goes for dereferencing a pointer that's been deleted (the pThread->get_id()
in your code).
A simple defensive technique is to set pointers to NULL as soon as they've been deleted, instead of letting them dangle. This may help catch some bugs of this type.
The above applies to pointers of any type, and not just boost::thread*
.
精彩评论