c++ - Difference between creating object with "new" or not. -
this question has answer here:
what difference between these 2 statements?
stringstream *mystream = new stringstream(s);
and
stringstream mystream(s);
i heard first return pointer , "dynamically" allocates memory. don't understand difference.
thank in advance
if inside function, in case:
stringstream mystream(s);
mystream allocated on stack. destroyed automatically @ end of scope. efficient.
in case:
stringstream *mystream = new stringstream(s);
mystream pointer object allocated on heap. destroyed when call delete mystream
.
most of time want use stack. efficient , memory gets freed automatically you. happens less type.
sometimes need more control. want function create object , have exist until explicitly delete it. these cases should rare, , modern c++ should use unique_ptr or shared_ptr make managing memory easier.
Comments
Post a Comment