【发布时间】:2016-10-17 10:16:53
【问题描述】:
如果我们创建一个map<int,int>,我们可以清除它但它仍然保留在内存中,对吧?例如
#include <map>
using namespace std;
int main(){
map<int,int> myMap;
myMap[1] = 2;
myMap.clear();
return 0;
}
但是如果我们设置一个指针而不是实际的map,我可以用delete 破坏它,但我不能以同样的方式填充地图:
#include <map>
using namespace std;
int main(){
map<int,int> *myMap = new map<int,int>;
// myMap[1] = 2;
delete myMap;
return 0;
}
取消注释myMap[1] = 2; 行最终会出现错误:
alvas@ubi:~$ g++ test.cpp test.cpp:在函数“int main()”中: test.cpp:8:14: error: no match for ‘operator=’(操作数类型是 ‘std::map’ 和 ‘int’) 我的地图[1] = 2; ^ 在 /usr/include/c++/5/map:61:0 包含的文件中, 来自 test.cpp:2: /usr/include/c++/5/bits/stl_map.h:296:7: 注意: 候选: std::map<_key _tp _compare _alloc>& std::map<_key _tp _compare _alloc>::operator=(const std::map<_key _tp _compare _alloc>&) [with _Key = int; _Tp = int; _比较 = std::less; _Alloc = std::allocator >] 运算符=(常量映射& __x) ^ /usr/include/c++/5/bits/stl_map.h:296:7:注意:没有已知的参数 1 从“int”到“const std::map&”的转换
如何在 C++ 中破坏 map?它是“可破坏的”吗?
另外,如何初始化/填充 map<> 指针的值?
【问题讨论】:
-
如果您使用
new,(*myMap)[1] = 2;可以解决问题。其余的在下面的 CinCout 答案中 -
同样的原因
int *i = new int(0); i += 5; delete i;不会在int上加 5。 -
“如果我们创建一个
map<int,int>,我们可以清除它,但它仍然保留在内存中,对吧?”,地图管理对象本身(可能是或两打字节,具体取决于您是在编译 32 位还是 64 位应用程序以及map实现是否添加了数据以支持调试)但map用于存储的数据元素的内存将被释放由应用程序重用。总而言之,在map上添加clear很少值得做。这与vector形成鲜明对比,后者往往会挂在曾经存储元素的内存中。 -
走第一条路线。当您清除地图时,其内容就消失了。它占用的存储空间不会超过指向它的指针(嗯,也许只是一点多一点)。不要让你的代码不必要地复杂化。
-
你有 15K 代表。您应该知道一次只问一个问题。
标签: c++ pointers initialization destructor stdmap