FileSystem()始终返回NULL,但我仍然可以通过g_System-> FileSystem()->;来调用EngineFile的函数;
我已经在VS2017和一个在线编译器上进行了测试。
显然,我的意图不是实际上不让FileSystem()返回NULL,因为原本打算将Systems.ef设置为EngineFile指针。在一个我正在从事的项目中,我不小心忘记了设置指针,并且在逐步执行其他一些代码时,我意识到它只是返回NULL并且仍在工作。
我已经将其压缩为一个文件,因此所有代码都在那里。
为什么这样做以及如何工作?
#include <iostream>
using namespace std;
class EngineFile
{
public:
EngineFile();
~EngineFile();
const char* GetFileData(const char* filename);
void ModifyBool(void);
private:
bool testmodify = false;
};
EngineFile::EngineFile()
{
}
EngineFile::~EngineFile()
{
}
void EngineFile::ModifyBool(void)
{
testmodify = true;
}
const char* EngineFile::GetFileData(const char* filename)
{
// open file filename
// stub function basically
return "This is the file data\n";
}
class Systems
{
public:
Systems();
~Systems();
EngineFile* const FileSystem(void);
private:
EngineFile* ef = NULL;
};
Systems::Systems()
{
}
Systems::~Systems()
{
}
static Systems* g_System;
EngineFile* const Systems::FileSystem(void)
{
return ef;
}
int main()
{
EngineFile* ef = new EngineFile();
g_System = new Systems();
// calling the function directly works as we would think
cout<<ef->GetFileData("test.txt");
// calling it through indirection with FileSystem returning NULL works
// why does this work? I feel like it should not work
cout << g_System->FileSystem()->GetFileData("test.txt");
// this will return null to show FileSystem returns null
EngineFile* efnulltest = g_System->FileSystem();
if (efnulltest == NULL)
cout << "efnulltest is NULL\n";
cout << "some extra text to show previous statement is still working\n";
// segfault as expected
g_System->FileSystem()->ModifyBool();
return 0;
}
之所以有效,是因为GetFileData不引用任何类数据。正在调用该函数,并在“ this”参数处传递(隐藏的)空ptr。由于该函数未使用“ this”,因此它就像是静态函数一样工作。