@ wrote... (10 years, 10 months ago)

Don't check a pointer before deleting it, just delete it.

// don't do this
if ( p ) delete p;

// just do this
delete p;

// ie: this doesn't crash or do anything bad
int* p = NULL;
delete p;

// but you probably need something like this
#define NUL_DEL( p ) { delete p; p = NULL; }

But seriously, this isn't the dark ages, you really want to be doing this.

std::shared_ptr<int> p;
p.reset(); // no need to set to NULL (or rather null_ptr)
Category: tech, Tags: cpp, programming, stl
Comments: 0
@ wrote... (11 years, 12 months ago)

Any Standard Template Library (STL) pro doesn't need to be told this but for somebody moving from MFC to the STL like me, the following would no doubt be handy.

The problem is that std::map creates a new object anytime you have map[key], even as an rvalue. So here is a super simple template function to quickly check if a map has a key.

template<typename T>
bool has_key( const T& map, typename const T::key_type& key )
    T::const_iterator iter = map.find( key );
    return iter != map.end();

// eg. has_key( my_map, "key" );

The tiny bit of magic here is the typename in typename const T::key_type&amp;. typename is required due to deep c++ voodoo that I really don't understand.

Or you could just…

map.count( key ) > 0;

Always learning.

Category: tech, Tags: cpp, stl
Comments: 0