c++ - Difference between creating object with "new" or not. -


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

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -