Storing local variable in std::map
I have a class Message and a class Cache. In Message::processMessage() fn. I create a instance of another class CacheRef(not shown below.) then I call Cache::cacheData(cacheRef)
Now, in Cache class, I have a map which has its key as CacheReference. I store the ref that I passed to cacheData fn. in this map.
class Message
{
private:
Key m_key;
public:
void processMessage(int a, int b, Cache *pCache)
{
CacheRef ref(a, b, m_key); //CacheRef is a class defined in same file
//some char *data - do processing an dfill it!!
pCache->cacheData(ref, data);
}
}
class Cache
{
public:
void cacheData(CacheRef &ref, const char* data)
{
CacheDir *dir;
std::map<<CacheRef, CacheDir*>::iterator it = m_dirs.find(ref);
if(it == m_dirs.end())
{
dir = new CacheDir();
m_dirs.insert(ref, dir);
}
}
std::map<CacheRef, CacheDir*> m_dirs; //CacheDir is some class defined in the same file
}
Now, the code is working absolutely fine. But I have this concern(not sure!!) that I am storing some local variable in map, which which cease to exist as soon as processMessage()fn. exits. So, am I accessing some invalid memory, is it just by luck that this code is working.
If this is wrong, what is the best way to achieve this behaviou开发者_Python百科r? I don't have boost on my system, so can't use shared_ptr for anything.
Because the 1st template parameter is a CacheRef (and not a reference or pointer to a CacheRef) then ref will be copied into the map when you do the insert. Hence, you won't be storing a reference to a local stack variable.
As long as there is an appropriate copy constructor or assignment operator for CacheRef then this will work ok.
As Stephen Doyle pointed out, you are actually storing a copy of the CacheRef
in the map, not a reference to the one passed to the cacheData()
method.
Whether this causes a problem or not depends on the definition of the CacheRef
class. If, for example, a CacheRef
holds a pointer or a reference to the Key
passed to the constructor, you will end up with an invalid pointer once the Message
instance is destroyed.
By the way, since you are storing dynamically allocated objects of CacheDir
in Cache::m_dirs
, you should make sure to delete
all values in the map in the Cache::~Cache()
destructor to avoid memory leaks.
精彩评论