c++ - 这些有什么区别?

标签 c++ pointers map

任何人都可以向我解释以下使用的在 map 容器中插入新对象的方法的区别吗?我已经知道指针等,我并没有真正深入到虚拟内存,只是基础知识(地址等)

#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;
}

最佳答案

在第一种情况下,pUser 是在堆栈上创建的,当它的名称超出范围时(即在下一个右花括号处),将被自动删除。一般来说,将指向堆栈对象的指针插入到容器中是不明智的,因为该对象将不复存在,而容器仍有指向它的值。在最好的情况下,这可能会导致崩溃。在最坏的情况下,它可能会导致代码中较远部分的错误不稳定且难以定位。

关于c++ - 这些有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11003081/

相关文章:

c - free() 函数不起作用

c++ - 如何在cpp中定义volatile元素的map

c++ - 如何从 TypeList 重建参数包

c++ - 无法使用原始套接字打印 TCP 响应

c++ - STL优先级队列非类类型编译错误

hibernate 外键映射多对一

c++ - 将 MSVS 2010 项目转换为 MSVS 2012 RC 但出现错误 "The C++ standard doesn' t 为此类型提供哈希”

c++ - 从 C++ STL 容器派生是否有任何真正的风险?

c - 我使用 restrict 限定符时出错

c++ - 使用 vector 构造函数分配动态内存