在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:37:02  来源:igfitidea点击:

Correct way to initialize a map and delete in C++

c++data-structuresstlmap

提问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 myMapis not a pointer, so the initialization with newis incorrect. Perhaps you are looking for:

这里myMap不是指针,所以初始化new不正确。也许您正在寻找:

  myMap = map<string,a>();

to copy into myMapa 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 myMapalready exists inside an instance of aClassand is constructed when its containing instance is constructed. You don't need to use newto 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++ 中,使数据成员成为值而不是指向其他对象的指针或引用更容易。