Can I free the char * string memory when I assign it to std :: string?

Can I free the memory of the end string char * after converting it to std :: string? For instance:

char* c_string;
c_string = strdup("This is a test");
std::string cpp_string;
cpp_string(c_string);
free(c_string); /* can I call free here? */
+5
source share
2 answers

Yes. std::stringcopies the main line C.

Source: table 67 from section 21.4.2 of the C ++ 11 project N3376.

+8
source

Yes. The constructor std::stringmakes a copy of the string passed to it.

See constructor # 4 on this page .

string (const char* s);    // from c-string

from c string

Copies a character sequence with a null character (C-string) specified by s.

+4
source

All Articles