C ++正确初始化和处理指向地图的方法

时间:2017-05-04 06:02:49

标签: c++ pointers dictionary

假设我想要一个指向我班级地图的私人指针。如果构造函数的参数(布尔值)为真,我希望它指向NULL。这是正确的做法吗? (如果我的布尔值为false,我在地图中添加第一个元素)

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;
}

EDIT 以下是我解决问题的方法:

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;
}

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

2 个答案:

答案 0 :(得分:0)

: _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
}

但是你仍然需要编写一个正确的拷贝构造函数和赋值运算符,整个事情感觉很蠢。考虑使用&#34;智能指针&#34;改为输入。

根据您的评论,您似乎想要一个(可能是空的)地图。没有指针,这可以更轻松地完成:

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

 private: 
  map<int, bool> _myMap;
}

现在我们不需要任何动态内存分配或自定义析构函数。

答案 1 :(得分:0)

暂时忽略使生活更艰难的理由...

$error = new Error($id, $from, $to);
return $response->withJson($error->error(), $error->code());

您可以使用以下内容:

  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
    }
  }

当您在对象中存储指向堆内存的指针时,不要忘记the Rule of Three