Deleting string object in C++

前端 未结 4 1312
挽巷
挽巷 2021-01-18 00:19

I have a string object in my C++ program declared as follows:

string str;

I have copied some data into it and done some operations. Now I w

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 01:13

    str.clear();
    

    or

    str = "";
    

    However, as stated in the comments, this does not guarantee (and, in fact, is rather unlikely) to actually return heap memory. Also not guaranteed to work, but in practice working well enough is the swap trick:

    std::string().swap(str);
    

    Still, implementations employing the small string optimization will retain a few bytes of stack space (and str itself of course also lives on the stack).

    In the end I agree with all comments saying that it is questionable why you want to do that. Ass soon as str goes out of scope, its data will be deleted automatically anyway:

    {
      std::string str;
    
      // work with str
    
    } // str and its data will be deleted automatically
    

提交回复
热议问题