指向 std::map 问题的指针
请考虑以下代码,我在将值插入 std::map 对象时遇到访问冲突。不知道为什么。 然而,正如您所看到的
std::map<int, int>
,我最初尝试
std::map<int, MSGTYPE>
使用相同的结果访问冲突。 (我知道枚举是 INT)。
// a common include file has this
// common.h
enum MSGTYPE
{
MSG_R1,
MSG_A1,
MSG_L1,
MSG_S1,
MSG_S2
};
typedef std::map<int, int> SYSMsgMap;
typedef struct _MYOBJ
{
int x1;
int x2;
SYSMsgMap XFerMap;
}MYOBJ;
我对这些结构的使用如下所示:
MYOBJ *cMYOBJ::AddNetwork(cvnet *net)
{
MYOBJ *ob;
ob = new MYOBJ();
// initialization code removed for this post/brevity
BuildMsgMap(ob->XFerMap);
// rest removed for this post/brevity
}
void cMYOBJ::BuildMsgMap(std::map<int, int> &mm)
{
mm.clear();
switch(NETTYPE)
{
case 1:
mm[ 1] = MSG_R1; <-- Access violation here!
mm[ 2] = MSG_A1;
mm[ 4] = MSG_L1;
mm[16] = MSG_S1;
mm[32] = MSG_S2;
break;
// rest removed...
}
Please consider the following code where I get an access violation inserting values into a std::map object. Not sure why. The code as you see it uses
std::map<int, int>
however, I initially tried
std::map<int, MSGTYPE>
with the same resulting access violation. (I know enums are INTs).
// a common include file has this
// common.h
enum MSGTYPE
{
MSG_R1,
MSG_A1,
MSG_L1,
MSG_S1,
MSG_S2
};
typedef std::map<int, int> SYSMsgMap;
typedef struct _MYOBJ
{
int x1;
int x2;
SYSMsgMap XFerMap;
}MYOBJ;
My use of these structures looks like so:
MYOBJ *cMYOBJ::AddNetwork(cvnet *net)
{
MYOBJ *ob;
ob = new MYOBJ();
// initialization code removed for this post/brevity
BuildMsgMap(ob->XFerMap);
// rest removed for this post/brevity
}
void cMYOBJ::BuildMsgMap(std::map<int, int> &mm)
{
mm.clear();
switch(NETTYPE)
{
case 1:
mm[ 1] = MSG_R1; <-- Access violation here!
mm[ 2] = MSG_A1;
mm[ 4] = MSG_L1;
mm[16] = MSG_S1;
mm[32] = MSG_S2;
break;
// rest removed...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ob
不会在ob = new MYOBJ;
之后和之前的某处被memset(ob, sizeof(MYOBJ), 0)
意外清除吗调用BuildMsgMap()
?(因为代码是遗留的,并且
memset
技巧经常在 C 中使用。)Doesn't
ob
get accidentally cleared withmemset(ob, sizeof(MYOBJ), 0)
somewhere afterob = new MYOBJ;
and before the call toBuildMsgMap()
?(Since the code is legacy and since
memset
trick is often used in C.)我认为因为 mm 是对 mm[0] 的引用,这就是您拥有的所有内存分配
所以对于 mm[1] 你需要进行插入。
或者你想做
希望这有帮助
i think since mm is a reference to the mm[0], and that is all the memory allocation you've got
so for mm[1] you need to do an insert.
or you'd like to do
hope this helps
我认为您遇到了访问冲突,因为 MYOBJ 没有定义构造函数,因此 SYSMsgMap 的构造函数没有被调用。向 MYOBJ 添加一个空的无参构造函数,看看它是否会改变一些东西,例如
I think you are getting an access violation because MYOBJ has no constructor defined, and therefore the constructor of SYSMsgMap is not getting called. Add an empty no-argument constructor to MYOBJ and see if it changes things, e.g.