2

Shared pointer is working without assign memory to Win class.

Code:

class Win
{
public:
    void disp()
    {
        //Do something
    }
};

int main()
{
    std::shared_ptr<Win> sharedptr;///holds null pointer
    sharedptr->disp();//// why its working
}

Why it's calling above function without assign memory to it. Could someone help me out of this?

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
Jeggu
  • 569
  • 2
  • 10
  • 26
  • 4
    It's undefined behavior, everything can happen including the behavior you are observing. – πάντα ῥεῖ Jan 13 '16 at 10:34
  • Possible duplicate of [How can C++ compiler optimize incorrect hierarchical downcast to cause real undefined behavior](http://stackoverflow.com/questions/10278199/how-can-c-compiler-optimize-incorrect-hierarchical-downcast-to-cause-real-unde) – BoBTFish Jan 13 '16 at 10:34
  • why it should not? The function isnt using any member variables. – 463035818_is_not_an_ai Jan 13 '16 at 10:34
  • 1
    See my answer on the other question. Basically, it is still wrong, but happens not to crash because the function doesn't do anything interesting with member data. – BoBTFish Jan 13 '16 at 10:35
  • Please see here http://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in-undefined-beha – lprazyan Jan 13 '16 at 11:30

1 Answers1

2

Try to do it like this:

#include <memory>
#include <iostream>
class Win
{
    public:
 void disp(){std::cout << x;}
 int x=5;
};

int main()
{
    std::shared_ptr<Win> sharedptr;///holds null pointer
    sharedptr->disp();//// why its working
}

You will not get 5. You may get anything. Like the guys in the comments said, it is undefined behaviour .

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160