C 正确的方法来初始化和处理映射指针
C++ correct way to initialize and handle pointer to map
,假设我想要一个私人指针到我的班级中的地图。如果我的构造函数(布尔值(是正确的,我希望它指向零。这是正确的方法吗?(如果我的布尔人是错误的,我在地图中添加了第一个元素(
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;
}
现在我们不需要任何动态内存分配或自定义驱动器。
相关文章:
- 错误处理.将系统错误代码映射到泛型
- C++在一个映射中存储不同的指针类型(并处理销毁)
- C++预处理会生成变量成员、资源库和映射
- C 正确的方法来初始化和处理映射指针
- 处理对存储在私有映射中的值的封装访问的标准方法,而不破坏C++中的抽象
- 如何自动将处理程序添加到全局映射
- 有没有办法在 MFC 中在运行时禁用消息映射处理程序
- c++处理结构的映射
- C++映射的指针在退出时自动释放,如何处理删除
- 如何使用move构造函数正确处理shared_ptr的映射
- 使用c++减少两个映射的处理时间
- 多重映射如何在内部处理重复键
- 有没有办法获取控件在 MFC 应用程序中映射到的处理程序函数
- 您如何处理使用 36 位映射的 IO
- 在c++中使用映射器处理派生类的创建
- 无法遍历模板映射.如何处理这个错误
- Boost::range用于处理容器的内容,并将映射中的值管道到下一个进程
- 如何处理带有底层排序向量的映射中的const值
- std::映射<>或std::vector<>在处理大型标志集时
- OpenMP对带有映射的循环进行并行处理