0

Code:

#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;
}

Output:

ptr:0
ptr:0x6ffddc
ptr:0
ptr:0

I am not able to understand why the pointer that I passed to function SetPointer in the singleton instance of GlobalClass which in turn is passed to PointerSetter is not visible when it comes out of PointerSetter. I need to access it in my main function. How is the pointer is being set to NULL or 0?

Raghu DV
  • 258
  • 5
  • 18
  • You're passing `ptr` by value to `PointerSetter` so even if you change the address it's pointing to, you're only changing it for the `PointerSetter` `ptr`. Pass your pointers by reference to solve this (or add another level of indirection) – scohe001 Oct 17 '17 at 16:17
  • Note that the only reason this situation is confusing is because you've named three completely different variables the same thing and therefore expect them to be the same. – scohe001 Oct 17 '17 at 16:19
  • Thank you. Got it! – Raghu DV Oct 17 '17 at 16:27
  • Also, using a local variable after returning from the function would be undefined behavior... if you try to dereference the variable. – Phil1970 Oct 17 '17 at 16:32

0 Answers0