Home > Back-end >  how to find the ways of handling pointer difference between ptr and ->
how to find the ways of handling pointer difference between ptr and ->

Time:03-30

what is the difference of pointers between and which is better in terms of memory management

void Loo(){ 
 Song* pSong = new Song(…);
 //…
 string s = pSong->duration;
}

and

void Hoo(){ 
 unique_ptr<Song> song2(new Song(…));
 //…
 string s = song2->duration;
}

CodePudding user response:

In the first case you need to call delete yourself and make sure it happens on all program control paths.

That is easier said than done. It's tempting to write delete pSong; just before the closing brace of the function and be done with it. But, for example, what happens if pSong->duration throws an exception? (Unlikely but certainly possible for member functions.)

With std::unique_ptr, delete will be called for you when it goes out of scope.

Although in this particular case Song song(...); may be more appropriate.

  • Related