简体   繁体   中英

Memory leak C++ string

I have a class eg

class test{

   public:
      somedatahere
      test();
     ~test();
   private:
       string mystring;

}

In this class the constructor reads the contents of a file in variable mystring.My question is :

Does mystring gets freed when the class destructs or I must free it manually? How can I free mystring ?

Since mystring is part of the object, it will go out of scope when the object does. There's no need to "manually" free it, and indeed you can't.

This would be different if mystring was a pointer to memory allocated with new (or new[] ), then you'd have to manually delete (or delete[] ) it from your destructor.

You only have to free what you allocate. new should be matched by delete , and new[] matched by delete[] .

If you don't do either, then a well-behaved class shouldn't require you to do the other. And yes, the standard library is well-behaved.

So no, you don't need to do anything. Let the std::string instance clean up after itself. (And of course, follow its example, and ensure that your own classes do the same)

假设你的构造函数只是直接分配到mystring而没有任何其他分配或做一些奇怪的事情,那么它将被析构函数正确释放。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM