Can anyone please explain me the difference about the below used methods to insert a new object in the map container? I already know about pointers and such, I’m not really deep into virtual memory, only the basics (addresses etc..)
#include "StdAfx.h"
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <map>
using namespace std;
class CUser
{
public:
CUser() { Init(); };
~CUser() {};
public:
BOOL m_bActive;
BOOL m_bLoggedIn;
SYSTEMTIME m_sysTime;
void Init();
};
void CUser::Init()
{
(*this).m_bActive = FALSE;
m_bLoggedIn = FALSE;
GetSystemTime( &m_sysTime );
}
int main(int argc, char *argv[])
{
map<DWORD, CUser*>mUserMap;
//what is the difference between this
{
CUser pUser;
pUser.m_bActive = FALSE;
pUser.m_bLoggedIn = FALSE;
GetSystemTime( &pUser.m_sysTime );
mUserMap.insert( make_pair( 351, &pUser ) );
}
//and this?
{
CUser *pUser = new CUser;
if( pUser )
{
pUser->m_bActive = TRUE;
pUser->m_bLoggedIn = TRUE;
GetSystemTime( &pUser->m_sysTime );
mUserMap.insert( make_pair( 351, pUser ) );
}
}
/* map<DWORD, CUser*>::iterator it = mUserMap.find( 351 );
if( it == mUserMap.end() )
std::cout << "Not found" << std::endl;
else
{
CUser *pUser = it->second;
if( pUser )
std::cout << pUser->m_sysTime.wHour << std::endl;
} */
return 0;
}
this creates a local object: your
pUservariable only exists inside the scope of this block, and ceases to exist when the last}is reached. That means its destructor is called, and the memory it lived in is reclaimed and may be reused.Now, when you store a pointer to this short-lived object in your map, you’re storing a problem. If you de-reference that pointer at any time after the closing
}of this block, you’re invoking undefined behaviour. It may work. It may work sometimes, and then start to fail. Basically, it’s a logical error and a good source of unpredictable bugs.here you explicitly create an instance which will outlive the enclosing scope, and all is good. You don’t need to check if
newreturnsNULLthough: it’ll throw an exception unless you explicitly request it not to.