if I have a string in a class, then memory is allocated. Do I have to开发者_运维知识库 destroy the string in the destructor? e.g.
class A { string Test; A() { Test = "hello world"; } A(string &name) { Test = name; } ~A() { // do I have to destroy the string here? } }
I'm an old c/c++ (pre stl) programmer and getting back into c++. Is the string destroyed automatically using some template magic?
tia, Dave
Yes, std::string's resources are cleaned up automatically. Standard strings and containers allocate/deallocate for you. HOWEVER, a container of pointers doesn't free up what those pointers point to. You have to loop through those yourself.
No. The string's destructor will be called once an instance of A goes out of scope.
You're not creating a pointer to the string, so Test will be allocated onto the stack (Assuming object A was allocated onto the stack). Thus, when it leaves scope, it will be deallocated automatically. If Test were a pointer it would be allocated on the heap and you would need to delete it in the destructor
You clean up your mess, and the standard library cleans up its mess. The memory that a std::string allocates is its mess.
The default behaviour for a destructor is to call destructors on each base and data member. Your string is a data member, so its destructor is called. Its destructor does everything that needs to be done here, so there is no more need (and in fact it would be very wrong) to clean anything up here than if you had the string as a local variable in main().
精彩评论