On 02/11/2010 08:30, DeMarcus wrote:
Hi,
How do you detect and handle invalid pointers to avoid segmentation
fault?
I have a callback scenario that looks like this. (using C++0x)
#include <functional>
#include <string>
#include <iostream>
#include <vector>
class SomeObject
{
public:
void fnc( const std::string& text )
{
std::cout << text << std::endl;
}
};
int main()
{
std::vector<std::function<void()> > callbacks;
SomeObject* s = new SomeObject;
callbacks.push_back( std::bind( &SomeObject::fnc, s, "Hello" ) );
callbacks.push_back( std::bind( &SomeObject::fnc, s, "World" ) );
callbacks.push_back( std::bind( &SomeObject::fnc, s, "The End" ) );
std::vector<std::function<void()> >::iterator i = callbacks.begin();
std::vector<std::function<void()> >::iterator end = callbacks.end();
for( int n = 0; i != end; ++i, ++n )
{
(*i)(); // Run the callback.
// At some point during this loop s is deleted. Could be from
// another thread.
if( n == 1 )
delete s;
}
return 0;
}
This callback trouble is just an example, but how are invalid pointers
detected in general? Is there a smart pointer that can handle this? Like
throwing an exception or just not run the callback.
Thanks,
Daniel
Well it's not a method that's necessarily suitable for every situation,
but you can sometimes deal with things like this by storing weak
pointers. When all shared pointers that point to the same thing are
reset elsewhere, that's like doing the delete above -- except that now
you can tell this has happened because locking the weak pointer will
fail. I've found it to be a useful approach at times.
HTH,
Stu