I have a fairly simple question that I cannot seem to find an answer for relating to C++ std::string and how it is instantiated with new. Now, I am well aware that any pointer returned from new should be subsequently deleted to prevent memory leak. My question comes from what happens when an existing pointer is subsequently used to instantiate a new string object. Please consider the following simplified example:
char* foo() {
char* ptr;
ptr = new char[ARBITRARY_VALUE];
...
ptr = strncpy("some null terminated string", ARBITRARY_VALUE)
...
return ptr;
}
int main() {
char* buf;
std::string myStr;
buf = foo();
myStr = new std::string(buf);
...do stuff
delete myStr;
delete buf; //Is this necessary?
return 0;
}
My question is simple: does deleting myStr also free the underlying memory used by buf or does buf need to be freed manually as well? If buf has to be freed manually, what happens in the case of anonymous parameters? As in:
myStr = new std::string(foo());
My suspicion is that the underlying implementation of std::string only maintains a pointer to the character buffer and, upon destruction, frees that pointer but I am not certain and my C++ is rusty at best.
Bonus question: How would this change if the class in question were something other than std::string? I assume that for any user created class, an explicit destructor must be provided by the implementer but what about the various other standard classes? Is it safe to assume that deletion of the parent object will always be sufficient to fully destruct an object (I try to pick my words carefully here; I know there are cases where it is desirable to not free the memory pointed to by an object, but that is beyond the scope of this question)?