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
If you want to zero the entire contents of the string, you can do it this way: memset(buffer,0,strlen(buffer)); but this will only work for zeroing up to the first NULL character. To clarify, the last method will work if buffer is is an array, but not if it is a pointer.
Return c_str of local std::stringWhen the std::string goes out of scope, its destructor is called and the memory is deallocated, so it is no longer safe to use the pointer.
A class needs a destructor if it acquires a resource, and to manage the resource safely it probably has to implement a copy constructor and a copy assignment. If these special functions are not defined by the user, they are implicitly defined by the compiler.
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.
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