pointers - Deleting Strings on the Heap Created from Char[] one the Heap in C++ -


i have simple question cannot seem find answer relating c++ std::string , how instantiated new. now, aware pointer returned new should subsequently deleted prevent memory leak. question comes happens when existing pointer subsequently used instantiate new string object. please consider 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 necessary?     return 0; } 

my question simple: deleting mystr free underlying memory used buf or buf need freed manually well? if buf has freed manually, happens in case of anonymous parameters? in:

mystr = new std::string(foo()); 

my suspicion underlying implementation of std::string maintains pointer character buffer and, upon destruction, frees that pointer not , c++ rusty @ best.

bonus question: how change if class in question other std::string? assume user created class, explicit destructor must provided implementer various other standard classes? safe assume deletion of parent object sufficient destruct object (i try pick words here; know there cases desirable not free memory pointed object, beyond scope of question)?

std::string may initialized c style null-terminated string (const char *). there no way std::string know if need const char * free()d, delete[]()d or neither, , stated won't.

use smart-pointers automatically delete dynamically allocated objects. there few different of these, each specialized particular purposes. have @ scoped_ptr, auto_ptr , shared_ptr. project have constraints on smart pointers use.

in context of c++ there never reason hold strings in manually declared char arrays, std::string safer use.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -