Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak C++ string

Tags:

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 ?

like image 944
opc0de Avatar asked Dec 12 '22 20:12

opc0de


2 Answers

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.

like image 163
unwind Avatar answered Dec 25 '22 05:12

unwind


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)

like image 29
jalf Avatar answered Dec 25 '22 05:12

jalf