如何引用 obj1 并在 NULL 时调用 show 方法
How is obj1 is referenced and calling show method if it is NULL
我正在尝试创建一次只能创建一个对象的类,所以我创建了私有构造函数和一个公共包装器 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
引用。
要"破坏"优化(并导致崩溃(,您可以执行以下操作之一:
virtual
show
功能进行修改- 引用非静态成员(例如 函数内部
temp
(
相关文章:
- 当使用通配符和null指针调用函数时,对输出的说明
- 如何引用 obj1 并在 NULL 时调用 show 方法
- 抛出 'std::logic_error' basic_string::_S_construct null 无效的实例后调用的终止
- FindResource 调用返回 RCDATA 类型的文本文件的 NULL
- (WMI)ExecMethod out 参数 - 无论调用的结果如何,ResultingSnapshot 都是 NULL
- 如何修复抛出"std::logic_error"实例后调用的终止 what(): basic_string::_M_construct null 无效
- 崩溃:分段故障:增强序列化加载 - 用null调用构造函数
- 调用类的方法时,类的指针"this"变为 null C++
- 抛出 'std::logic_error' what() 的实例后调用的终止:basic_string::_S_construct null 无效
- 构造函数中的 Malloc 在通过 New 调用时返回 NULL
- rand()在通过函数调用时生成相同的随机数集(即使在使用srand(time(NULL)进行种子设定之后)
- 以 NULL 为参数的调用中的重载解析
- 如何避免错误:在抛出 what() 的实例后终止调用'std::logic_error':basic_string::_S_construct null 无效
- SuiteSparse(4.5.1) 的 SPQR - 调用 cholmod_allocate_triplet 总是返回 NULL
- 从转储中获取调用堆栈的几乎所有帧中的此指针 NULL 表明什么
- Rand() 是相同的数字生成器,即使我调用了 srand(time(NULL))
- Delphi - 从 dll 调用转换(读取)C++ NULL 终止数组
- 当 0 或 NULL 通过模板间接传递给共享指针(shared_ptr OR unique_ptr)时,调用函数失败
- 调用不访问 null 对象指针上数据的方法有时有效,有时崩溃。为什么它不总是崩溃?
- 正在对未定义的NULL指针调用函数