2017-05-04 97 views
-1

假设我想要一个私人指针指向我班的地图。如果我的构造函数(一个布尔值)的参数为true,我希望它指向NULL。这是否是正确的做法? (如果我的布尔是假的,我在地图上添加第一个元素)C++正确初始化和处理指向地图的指针

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

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

+2

第一件事第一件事。为什么指针?为什么动态分配? –

+0

我想要一个指针,因为我希望能够检查我的地图是否指向NULL。我不确定我的地图指针的正确初始化方式。 – klaus

+0

那么,你的意思是什么“NULL”?为什么你要“指向NULL”? –

回答

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 
} 

但是你仍然必须写一个正确的拷贝构造函数和赋值操作符,整个事情感到恶心。考虑使用“智能指针”类型。


根据你的意见,你似乎想要一个(可能是空的)地图在你的班级。没有指针可以做得更容易:

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

private: 
    map<int, bool> _myMap; 
} 

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

+0

谢谢。然后,我将保持_myMap(0)在构造函数中,并删除新的。但是如果我想添加元素到我的地图中,我需要像我一样去引用'_myMap',对吧? – klaus

+2

@klaus所以你希望指针指向NULL,但你不知道这意味着什么。看来你不明白指针是什么,所以也许你应该重新考虑你是否需要代码。 – juanchopanza

0

暂时忽略了使生活难度比它必须是理...

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

不要忘记the Rule of Three当你在你的对象中存储一个指向堆内存的指针时。