Friday, 15 June 2012

c++ - Difference between allocating memory in struct and main? -



c++ - Difference between allocating memory in struct and main? -

i have 2 simple structures this:

struct point{ double x, y; };

what difference between defining this

struct circle{ point *p; float radius; };

and this

struct circle{ point *p = new point; float radius; };

is there advantages if utilize first sample , in main function

circle *c = new circle; c -> p = new point;

this:

struct circle{ point *p = new point; float radius; };

uses c++11 in-class initialization. means default, if no other constructor otherwise (there none in example), p set new point constructed circle. equivalent less lines of code illustration explicitly set p after creating circle.

of course, illustration code you've provided, you'd improve off using value instead of pointer:

struct circle{ point p; float radius; };

then there point within circle, , won't have have long awkward conversation resource management, memory leaks, etc.

c++ pointers new-operator

No comments:

Post a Comment