访问嵌套类内的空映射时发生访问冲突
Access violation when accessing an empty map inside a nested class
我有一些包含三个类的代码。相关类别结构包括以下内容:
- class1包含指向class2实例的指针
- class2包含一个私有class3类和一个访问对类3的引用的函数
- class3包含一个私有映射类和一个用于检查映射是否为空的函数
我遇到的问题是,当我这样设置时,我会遇到访问违规:
bool result = class1->class2->GetProperties().CheckEmpty();
但如果我这样设置,我不会有任何错误:
bool result = class2->GetProperties().CheckEmpty();
为什么添加另一个类层会突然导致这个问题?
这是我用来重现错误的代码。in main中的两行不会产生错误,但对它们进行注释并取消对另外两行的注释,您就会得到错误。
#include "stdafx.h"
#include <map>
class PropertySet
{
public:
PropertySet::PropertySet(){};
PropertySet::~PropertySet(){};
bool CheckEmpty() const { return properties.empty(); }
private:
std::map< std::string, std::string > properties;
};
class Tile
{
public:
Tile::Tile() {};
Tile::~Tile() {};
// Get a set of properties regarding the tile.
const PropertySet &GetProperties() const { return properties; }
private:
PropertySet properties;
};
class Tileset
{
public:
Tileset::Tileset(){};
Tileset::~Tileset(){};
Tile* tile;
};
int main()
{
bool test = false;
//NO error-----------------------------
Tile* t = new Tile();
test = t->GetProperties().CheckEmpty();
//-------------------------------------
//ERROR--------------------------------
//Tileset* t = new Tileset();
//test = t->tile->GetProperties().CheckEmpty();
//-------------------------------------
delete t;
return 0;
}
构造新Tileset时,指向Tile的指针未初始化。
Tileset::Tileset(){};
Tileset::~Tileset(){};
应该是
Tileset::Tileset(){ tile = new Tile(); };
Tileset::~Tileset(){ delete tile; };
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 如何在C++中访问有序映射中的键的范围/间隔?
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 线程时访问静态映射时出现隔离错误
- 插入数组时违反写访问冲突
- 尝试将纹理映射到 GLSL 中的三角形时出现访问冲突
- 在全局映射中插入元素时发生访问冲突
- 访问嵌套类内的空映射时发生访问冲突
- "detects_simple_anagram"中的致命错误:地址 0x00000000 处的内存访问冲突:故障地址处没有映射
- 在全局映射中插入元素时发生访问冲突