代码:
#include <iostream>
class GlobalClass
{
static GlobalClass *s_instance;
public:
static GlobalClass *instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
void SetPointer(void *ptr)
{
this->PointerSetter(ptr);
std::cout << "ptr:" << ptr << std::endl;
}
void PointerSetter(void *ptr)
{
int Value = 1;
ptr = &Value;
std::cout << "ptr:" << ptr << std::endl;
}
};
GlobalClass *GlobalClass::s_instance = 0;
int main()
{
void *ptr=NULL;
std::cout << "ptr:" << ptr << std::endl;
GlobalClass::instance()->SetPointer(ptr);
std::cout << "ptr:" << ptr << std::endl;
return 0;
}
输出:
ptr:0
ptr:0x6ffddc
ptr:0
ptr:0
我无法理解为什么在SetPointer
的单例实例中传递给函数GlobalClass
的指针反过来传递给PointerSetter
的指针在出现时不可见PointerSetter
。我需要在main
函数中访问它。
如何将指针设置为NULL或0?