std::map with pointers
Sometimes I want to use a std::map to store pointers to objects. The problem however is that this does not work:
1
2
3
4
5
6
std::map<std::string, char*> map1;
...
if (map1["key"] != NULL)
{
// object seems to exist, this will not work though..
}
A pointer that is not explicitly assigned a value holds a random value by default. Running the sample multiple times and printing the pointer clearly shows that. How I wish there was a pointer that can make a distinction between valid/invalid. Hold on...
1
2
3
4
5
6
std::map<std::string, boost::shared_ptr<char> > map2;
...
if (map2["key"])
{
// object really exists! hooray
}
Why does this work? Well that's because boost::shared_ptr has an implicit conversion operator to bool that tells us if the shared_ptr was properly assigned a value (or not). The default value is 'false' because it's an empty shared_ptr. Problem solved!
This post is licensed under CC BY 4.0 by the author.