在 C++ 中初始化映射和删除的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10918514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to initialize a map and delete in C++
提问by SurenNihalani
I am trying to create a static map declared in the constructor of my class. This map is to be initialized and filled with data in one method and free'd in another method. Is this the correct way to do it?
我正在尝试创建在我的类的构造函数中声明的静态映射。该地图将在一种方法中初始化并填充数据,并在另一种方法中释放。这是正确的方法吗?
using namespace std;
#include <map>
struct a {
string b;
string c;
}
class aClass:public myClass
{
public:
aClass();
virtual ~aClass();
private:
map<string, a> myMap;
void method(int a);
void amethod(int b);
}
void aClass::method(int a)
{
myMap = new map<string, a>;
// Addition of elements;
}
void aClass::amethod(int b)
{
// retrival of elements
myMap.clear();
delete myMap;
}
回答by K-ballo
map<string, a> myMap;
....
myMap = new map<string, a>;
Here myMap
is not a pointer, so the initialization with new
is incorrect. Perhaps you are looking for:
这里myMap
不是指针,所以初始化new
不正确。也许您正在寻找:
myMap = map<string,a>();
to copy into myMap
a default initializedmap.
复制到myMap
一个默认初始化的地图。
Note that you don't need (and in fact can't) delete myMap
, as is not a pointer. It's a member variable, and the compiler will take care of automatically destroying it when your class is destroyed.
请注意,您不需要(实际上也不能)delete myMap
,因为它不是指针。它是一个成员变量,当你的类被销毁时,编译器会自动销毁它。
回答by Jonathan Wakely
void aClass::method(int a)
{
myMap.clear(); // ensure it starts off empty
// Addition of elements;
}
void aClass::amethod(int b)
{
// retrival of elements
myMap.clear(); // maybe not necessary
}
The object myMap
already exists inside an instance of aClass
and is constructed when its containing instance is constructed. You don't need to use new
to create it, that's a Java and C# feature, where variables are just references to some instance on the heap and everything is garbage-collected. In C++ it's easier to make data members a value rather than a pointer or reference to some other object.
该对象myMap
已存在于 的实例中,aClass
并且在构造其包含实例时构造。您不需要使用new
来创建它,这是一个 Java 和 C# 功能,其中变量只是对堆上某个实例的引用,并且所有内容都被垃圾收集。在 C++ 中,使数据成员成为值而不是指向其他对象的指针或引用更容易。