C ++ memory leak error

I have a class like

class test{ public: somedatahere test(); ~test(); private: string mystring; } 

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

Does mystring release happen when the class destroys or do I have to release it manually? How can I release a secret?

+4
source share
3 answers

Since mystring is part of the object, it will go beyond the scope of the object. There is no need to manually release it, and you really cannot.

It would be different if mystring was a pointer to the memory allocated using new (or new[] ), then you would have to manually delete (or delete[] ) to remove it from the destructor.

+7
source

You only need to free what you select. new must match delete , and new[] matches delete[] .

If you do not do this, the class itself should not require another from you. And yes, the standard library behaves well.

No, you donโ€™t have to do anything. Let the std::string instance clear after itself. (And of course, follow his lead and make sure your own classes do the same)

+5
source

Assuming your constructor simply assigns directly to mystring without any other allocation or does something weird, then yes, it will be correctly freed by the destructor.

+1
source

Source: https://habr.com/ru/post/1446166/


All Articles