Can I free the memory of the char* pointed string after I have convert it to a std::string? For example:
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? */
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
You can't really "assign a string" to a char * , because although a char* parameter is sometimes referred to as a "string parameter", it isn't actually a string, it's a pointer (to a string).
std::string is just a normal class1, so the usual rules apply. If you allocate std::string objects on the stack, as globals, as class members, ... you don't need to do anything special, when they go out of scope their destructor is called, and it takes care of freeing the memory used for the string automatically.
While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.
Yes. std::string
copies the underlying C string.
Source: Table 67 of §21.4.2 of C++11 draft N3376.
Yes. The std::string
constructor makes 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 the null-terminated character sequence (C-string) pointed by s.
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