jeudi 31 octobre 2019

How does shared_ptr work in c++ without initialization

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.

Aucun commentaire:

Enregistrer un commentaire