is the following code 100% correct? I’m coding a game and CItemElem is a class that holds Item informations, such as power etc. I want to store pointers from the items into an instance of another class named CChatLink. Please have a look:
[.H]
#pragma once
class CChatLink
{
private:
CChatLink(){}; //no new usage or global object allowed
~CChatLink(){};
public:
BOOL InsertChatLink( TCHAR* szText, CItemElem *pItemElem );
map<std::string,CItemElem*>m_mChatLink;
static CChatLink* GetInstance( void )
{
static CChatLink pObj;
return &pObj;
}
};
[.cpp]
#include "StdAfx.h"
#include "Item.h"
#include "CChatLink.h"
BOOL CChatLink::InsertChatLink( TCHAR *szText, CItemElem* pItemElem )
{
if( pItemElem && szText )
{
std::string szInsert( szText );
CItemElem *pItem = new CItemElem; //as far as I know, it must be allocated on the heap to be inserted ^^
pItem = pItemElem;
m_mChatLink.insert( make_pair( szInsert, pItem ) );
return TRUE;
}
return FALSE;
}
Can I store the std::string into the map that way?
(I’m currently studying C++ so please go easy on me.)
Yes you have a memory leak right here:
You just lost the address to where the object was allocated. Why are you doing this anyways if the item to be inserted is being passed as an argument? It is not clear from your code.
Is this what you meant instead?:
EDIT:
It sounds like
pItemElemis a pointer to an object that has been allocated on the stack. You could either changem_mChatLinkto astd::map<std::string, CItemElem>(not aCItemElem*) OR this:You will need to
deleteall theseCItemElems in your destructor.