简体   繁体   English

正确的初始化地图和在C ++中删除的方法

[英]Correct way to initialize a map and delete in C++

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;
 }
  map<string, a> myMap;
  ....
  myMap = new map<string, a>;

Here myMap is not a pointer, so the initialization with new is incorrect. 这里myMap不是指针,因此使用new进行初始化是不正确的。 Perhaps you are looking for: 也许您正在寻找:

  myMap = map<string,a>();

to copy into myMap a default initialized map. 默认初始化地图复制到myMap

Note that you don't need (and in fact can't) delete myMap , as is not a pointer. 请注意,您不需要(实际上不能) delete myMap ,因为它不是指针。 It's a member variable, and the compiler will take care of automatically destroying it when your class is destroyed. 它是一个成员变量,编译器会在你的类被销毁时自动销毁它。

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. 对象myMap已经存在的一个实例内aClass和包含它的实例被构造时的构造。 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. 您不需要使用new来创建它,这是一个Java和C#特性,其中变量只是对堆上某个实例的引用,并且所有内容都是垃圾收集的。 In C++ it's easier to make data members a value rather than a pointer or reference to some other object. 在C ++中,更容易使数据成员成为值而不是指针或对其他对象的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM