How to properly free a std::string from memory

后端 未结 6 668
余生分开走
余生分开走 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:50

    void foo() {
        string* myString = new string("heap-allocated objects are deleted on 'delete myString;'");
        cout << *myString << endl;
        delete myString;
    }
    

    or better yet, avoid pointers when possible and use automatic variables:

    void foo() {
        string myString("stack-allocated string is automatically deleted when myString goes out of scope");
        cout << myString << endl;
    }
    

提交回复
热议问题