【发布时间】:2016-10-09 07:24:41
【问题描述】:
我是 C++ 新手,所以我还不太了解它
所以基本上我有这个代码
头文件
class Application{
public:
static Application& getInstance()
{
return *mInstance;
}
Application();
void run();
protected:
static Application* mInstance;
源文件
Application* Application::mInstance;
Application::Application()
{
mInstance = this;
}
那我做
Application::getInstance().run();
Application 类的构造函数何时运行?
它似乎在视觉工作室工作。
所以我的问题是为什么这行得通?
为什么 getInstance 不返回空指针?因为我从来没有实例化过这个类。
这个代码标准吗?
这适用于任何现代 c++ 编译器吗?
【问题讨论】:
-
你在getInstance之前的任何地方都创建了对象吗?
-
构造函数运行时,不是“类的构造函数”,而是该类的特定对象的构造函数。您到目前为止发布的代码示例不会创建该类的任何对象。所以,构造函数永远不会运行。
-
Why does getInstance does not return a null pointer? since i have never instantiated the class.好吧,因为 UB。您的代码完全错误。 -
@deviantfan: 不,我在调用 getInstance 之前不创建任何对象
标签: c++