c++ - Why using different (shared_ptr and normal) pointer constructors on the same class I get different results? -
inspired this question wrote own little program (using code this answer) , discovered things confused me. namely:
having classes:
class { public: a(){} int i; int j; }; class b { public: b() = default; int i; int j; };
i wrote 4 usages of classes different object construction usages:
//1 a* pa = new a(); // followed delete pa b* pb = new b(); // followed delete pb //2 shared_ptr<a> pa = make_shared<a>(); shared_ptr<b> pb = make_shared<b>(); //3 shared_ptr<a> pa ( new a() ); shared_ptr<b> pb ( new b() ); //4 shared_ptr<a> pa ( new ); shared_ptr<b> pb ( new b );
and after have used them print values so:
for( int = 0; < 3; ++i) { ...1..2..3..4 cout << "a : " << pa->i << "," << pa->j << endl; cout << "b : " << pb->i << "," << pb->j << endl; }
what have received on output surprised me:
//1 : 0,0 b : 0,0 : 7388176,0 b : 0,0 : 7388208,0 b : 0,0 //2 : 0,0 b : 0,0 : 0,0 b : 0,0 : 0,0 b : 0,0 //3 : 0,0 b : 0,0 : 25848848,0 b : 0,0 : 25848880,0 b : 0,0 //4 : 0,0 b : 0,0 : 39619600,0 b : 39619664,0 : 39619632,0 b : 39619696,0
while first 1 described in aforementioned question's answers happening in //2
, //3
, //4
?
i used gcc 4.9.2 , 5.1.0 on ubuntu 64 bit same results.
your first 3 code snippets value-initialize objects constructed.
if class's default constructor not user-provided, value-initialization performs zero-initialization, , call default constructor; otherwise, calls default constructor.
now apply discussion in question linked.
for make_shared
case see zeroes in both cases, that's 1 possible manifestation of undefined behavior. nothing more.
the final snippet default-initializes objects constructed, which, object of class type, means calling default constructor, in each case performs no initialization.
Comments
Post a Comment