How to properly free a std::string from memory

后端 未结 6 664
余生分开走
余生分开走 2021-01-30 05:35

What\'s the best way to delete an std::string from memory allocated on the heap when I\'m done using it? Thanks!

6条回答
  •  梦谈多话
    2021-01-30 05:55

    You can treat std::string like any other class. Use new for allocation, and delete once you're done with it. With C++11, I do not recommend usage of new and delete in most cases. If you need to allocate the string on heap, use std::shared_ptr to wrap it:

    std::shared_ptr my_string = std::make_shared(std::string("My string"));
    

    As soon as all the copies of my_string go out of scope, the associated memory is going to be deleted automatically.

提交回复
热议问题