如何组合 CString、CSimpleMap 和 CSimpleArray
typedef ATL::CSimpleMap<WTL::CString,WTL::CString> _Map;
ATL::CSimpleArray<_Map> g_arrMaps;
_Map map;
map.Add(WTL::CString(L"first"),WTL::CString(L"second"));
map.Add(WTL::CString(L"first2"),WTL::CString(L"second2"));
g_arrMaps.Add(map);
//another place _Map has been destructed
for(int i=0;i<g_arrMaps.GetSize();i++){
_Map m=g_arrMaps[i];
for(int y=0;y<m.GetSize();y++){
ATLTRACE(m.GetKeyAt(y)); //error
}
}
当我想追踪数据时出现错误。
typedef ATL::CSimpleMap<WTL::CString,WTL::CString> _Map;
ATL::CSimpleArray<_Map> g_arrMaps;
_Map map;
map.Add(WTL::CString(L"first"),WTL::CString(L"second"));
map.Add(WTL::CString(L"first2"),WTL::CString(L"second2"));
g_arrMaps.Add(map);
//another place _Map has been destructed
for(int i=0;i<g_arrMaps.GetSize();i++){
_Map m=g_arrMaps[i];
for(int y=0;y<m.GetSize();y++){
ATLTRACE(m.GetKeyAt(y)); //error
}
}
I got error when I want to trace out the data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CSimpleMap
有一个编译器提供的无用的复制构造函数,它仅将指针复制到其内部缓冲区。当您将映射添加到CSimpleArray
时,两个映射实际上共享相同的数据结构。当一个超出范围并释放内存时,会导致另一个也变得无效。在您的情况下,您可能会幸运地访问已释放的CSimpleMap
缓冲区,但该缓冲区包含CString
,一旦删除,它们就会释放其内部缓冲区,即 char 数组。您可以做什么:
CSimpleMap
。它实际上执行串行查找,并且具有可怕的默认复制构造函数。使用 CAtlMap 来代替 - 它的复制构造函数是私有的,所以你会知道你在编译时做错了什么。CSimpleArray
包含指向映射的指针:CSimpleArray<_Map*>
。这意味着您需要进行额外的内存管理,但您可以避免缓冲区共享。CSimpleMap
或CAtlMap
,并为其提供一个合适的复制构造函数。CSimpleMap
has a good-for-nothing compiler-supplied copy constructor, which merely copies the pointer to its internal buffer. When you add a map to yourCSimpleArray
, both maps actually share the same data structure. When one goes out of scope and releases memory, it causes the other to become invalid as well. In your case, you might got lucky with accessing already freedCSimpleMap
buffer, but that buffer containsCString
s, and once deleted they have released their internal buffers, namely the char arrays.What you can do:
CSimpleMap
. It actually does a serial lookup, and it has that horrible default copy constructor. Use CAtlMap instead - its copy constructor is private, so you'll know you're doing something wrong in compile time.CSimpleArray
contain pointers to maps:CSimpleArray<_Map*>
. This means extra memory management on your part, but then you avoid the buffer sharing.CSimpleMap
orCAtlMap
, and provide it a decent copy constructor.您不能将具有重要复制构造函数的类型与简单 ATL 集合一起使用。这些集合使用
calloc
/_recalloc
来管理其内存,并且不会正确复制元素。You can't use types that have non-trivial copy constructors with the simple ATL collections. Those collections use
calloc
/_recalloc
to manage their memory and do not bother copying elements properly.