Reputation: 11768
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 ?
Upvotes: 4
Views: 228
Reputation: 2128
Assuming your constructor just assigns directly into mystring
without any other allocation or doing something weird, then yes it will be deallocated properly by the destructor.
Upvotes: 1
Reputation: 399793
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.
Upvotes: 7
Reputation: 247919
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)
Upvotes: 5