0

I was going through shared_ptr and came across this.

class A
{
    public:
        A() { cout << "In constructor" << endl; }
        ~A() { cout << "Destructor" << endl; }
        void fun() { cout << "In fun... " << endl; }
};
int main()
{
    shared_ptr<A> a;
    a->fun();
    return 0;
}

The output of this is - In fun...

I would like to understand how is this giving above output.

On further experimentation if there is a member variable and being used in this function it throws an SIGSEGV.

class A
{
    public:
        A() { cout << "In constructor" << endl; }
        ~A() { cout << "Destructor" << endl; }
        void fun() { a = 5 ; cout << "In fun... " << endl; }
        int a;
};

int main()
{
    // A::fun();
    shared_ptr<A> a;
    a->fun();
    return 0;
}

Above throws SIGSEGV stating this pointer is null.

1 Answers1

6

The code in both cases has undefined behavior because the raw pointer of the shared_ptr pointer is initialized by nullptr.

In the second case the code tried to access memory of the data member a using nullptr.

In the first case the code executed without a failure only due to there is no access to the memory of the object. However the code has undefined behavior because you may not use a null-pointer to access non-static members of a class..

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I understand the part about being initialized to nullptr but for the first case, how is it allowing function call and printing. I tried in Visual C++ and g++ and seeing this behavior consistently. – Sanjay Kumar Oct 31 '19 at 12:19
  • 1
    @SanjayKumar In fact the function is executed as a non class member function with an addition argument that is equal to this. As within the function in the first case the pointer is not used to access then there is no failure. However according to the C++ Standard it is undefined behavior. – Vlad from Moscow Oct 31 '19 at 12:20
  • In that case, this statement should not throw compilation error, A::fun() – Sanjay Kumar Oct 31 '19 at 12:23
  • @SanjayKumar It is not a static member function. You may not call it this way. – Vlad from Moscow Oct 31 '19 at 12:24