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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With