J.Wei J.Wei - 9 months ago 39
C++ Question

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

My question is:
When I introduce the

into class B, it would give other data member the zero-initialization.

The code is given below:

class A
int data_a;

class B
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
has a default ctor so B would generated an implicit default ctor.

Now I didn't introduce the
so the output would be:


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


Why? What makes this happen?

Thanks in advance.

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

Answer Source

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.