如何引用 obj1 并在 NULL 时调用 show 方法

How is obj1 is referenced and calling show method if it is NULL

本文关键字:NULL 调用 show 方法 并在 obj1 何引用 引用      更新时间:2023-10-16

我正在尝试创建一次只能创建一个对象的类,所以我创建了私有构造函数和一个公共包装器 getInstance(( 方法,该方法将为此类创建对象,代码如下

#include <iostream>
using namespace std;
class sample
{
static int cnt;
int temp;
private: sample()
{
//temp++;
cnt++;
cout<<"Created "<<++temp<<endl;
}
public:
void show()
{
cout<<"Showing n";
}
static sample* getInstance()
{
cout<<"count is "<<cnt<<endl;
if(cnt<1)
return (new sample());
else
return NULL;
}
};
int sample::cnt=0;
int main()
{
// cout<<"Hello World";
sample *obj = sample::getInstance();
obj->show();
sample *obj1 = sample::getInstance();
if(obj1 == NULL)
cout<<"Object is NULLn";
obj1->show();
return 0;
}

obj1->show()是如何被召唤的?
输出:

count is 0
Created 1
Showing
count is 1
Object is NULL
Showing

在真空中,这只是因为你的函数:

public:
void show()
{
cout<<"Showing n";
}

实际上不要尝试对对象做任何事情 - 要了解为什么这正确的心态,只需将成员函数视为将对象作为第一个参数的自由函数的抽象:

void show(Object* this)
{
cout<<"Showing n";
}

现在很容易理解为什么这会起作用,因为您不使用this- 空指针。

如果你换成什么唉。

public:
void show()
{
cout<< this->temp << "Showing n";
}

您的程序几乎肯定会崩溃。

几乎可以肯定的是,编译器正在通过内联来优化对show的调用。此外,它还可以使其成为"伪静态"函数,因为内部没有对任何其他类成员show引用。

要"破坏"优化(并导致崩溃(,您可以执行以下操作之一:

  1. virtualshow功能进行修改
  2. 引用非静态成员(例如 函数内部temp(
相关文章: