访问嵌套类内的空映射时发生访问冲突

Access violation when accessing an empty map inside a nested class

本文关键字:访问冲突 映射 嵌套 访问      更新时间:2023-10-16

我有一些包含三个类的代码。相关类别结构包括以下内容:

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