J.Wei
J.Wei

Reputation: 81

C++ std::shared_ptr would initialized other member data in the class

My question is: When I introduce the std::shared_ptr into class B, it would give other data member the zero-initialization.

The code is given below:

class A
{
    public:  
        int data_a;  
        A():data_a(0){}  
    };

    class B 
    {
    public:
        int data_b;
        A a; 
        //shared_ptr<B> ptr_b; // the key point here
    };

    int main()
    {
        B b;
        cout << b.data_b << endl;
    }
}

As member a has a default ctor so B would generated an implicit default ctor.
Now I didn't introduce the shared_ptr so the output would be:

-858993460

But once I introduced the share_ptr into the codes, the output became:

0

Why? What makes this happen?

Thanks in advance.

I am using microsoft blend for VS community 2015 version 14.025425.01 update 3.

Upvotes: 0

Views: 165

Answers (1)

David G
David G

Reputation: 96810

The implicit-default constructor will default-initialize your scalar data members, so they will have an indeterminate value. As for your test case, it has undefined behavior as you're trying to print an uninitialized object. Any output whatsoever is valid.

Upvotes: 1

Related Questions