D
DeMarcus
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
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