C 正确的方法来初始化和处理映射指针

C++ correct way to initialize and handle pointer to map

本文关键字:处理 映射 指针 初始化 方法      更新时间:2023-10-16

,假设我想要一个私人指针到我的班级中的地图。如果我的构造函数(布尔值(是正确的,我希望它指向零。这是正确的方法吗?(如果我的布尔人是错误的,我在地图中添加了第一个元素(

using namespace std;
#include <map>
class Class {
 public:
  Class(bool a)
   : _myMap(0) {
    if (a) {
      _myMap = new map<int, bool>(); // initialized to NULL
    } else {
      (*_myMap)[0] = true; // added a first key-value to map
    }
  }
  ~Class() {
   delete _myMap;
 }
 private: 
  map<int, bool>* _myMap;
}

编辑这是我解决问题的方式:

using namespace std;
#include <map>
class Class {
 public:
  Class(bool a)
   : _myMap(0) { // map initialized to NULL
    if (a) {
      _myMap = new map<int, bool>();
    }
  }
  ~Class() {
   delete _myMap;
  }
  void addValue(bool b, int i) {
     if (_myMap != 0) {
        (*_myMap)[i] = b;
     }
  }
 private: 
  map<int, bool>* _myMap;
}

回答我问我为什么需要指针的人,而不是简单的地图:当我使用组件类时,我不想添加值(构造函数中的a(在构造函数中(为false,即如果我的地图指向null。

忽略一会儿,使生活更艰难的理由比...

  Class(bool a)
   : _myMap(0) {
    if (a) {
      // You are not doing what your comment says
      // you want to do.
      _myMap = new map<int, bool>(); // initialized to NULL
    } else {
      // This is bad.
      // myMap is still a null pointer. You are dereferencing
      // a null pointer. Only bad things can happen with this.
      (*_myMap)[0] = true; // added a first key-value to map
    }
  }

您可以沿着:

的线路使用一些东西
  Class(bool a)
   : _myMap(nullptr) {  // Use nullptr for pointers.
    if (a) {
      // There is nothing to do.
    } else {
      // Allocate memory for myMap
      _myMap = new map<int, bool>(); // initialized to NULL
      // Now you can dereference the pointer.
      (*_myMap)[0] = true; // added a first key-value to map
    }
  }

当您存储在对象中存储器的指针时,不要忘记三个规则。

: _myMap(0)初始化指针到 NULL

然后

_myMap = new map<int, bool>(); // initialized to NULL

分配map并指向_myMap。那是无效指针的对立面。new的返回值保证不是NULL

else分支中,您做

(*_myMap)[0] = true;

这具有不确定的行为。您正在删除_myMap,这是一个空指针。

结论:不,这是不正确的。


您可以通过:

来修复此特定的代码
if (!a) {
  _myMap = new map<int, bool>();
  (*_myMap)[0] = true; // added a first key-value to map
}

但是您仍然必须编写一个正确的复制构造函数和分配运算符,整个事情都很奇怪。考虑使用"智能指针"类型。


根据您的评论,您似乎需要一堂(可能是空的(地图。没有指针,这可以容易得多:

class Class {
 public:
  Class(bool a)
  {
    if (!a) {
      _myMap[0] = true; // added a first key-value to map
    }
  }
 private: 
  map<int, bool> _myMap;
}

现在我们不需要任何动态内存分配或自定义驱动器。