I have a doubt on basic C++ usage. The code below, compiled with gcc/LInux, prints out correctly.
The string test
goes out of scope so also its c_str()
value should be invalid isn't it? Am I wrong or do I have misunderstood the const char*
meaning?
#include <iostream>
int main(){
const char* a = "aaaa";
std::cout << a;
{ std::string test("bbbb");a=test.c_str();}
std::cout << a;
a = "cccc";
std::cout << a;
}
aaaabbbbcccc
// print out without any problem
You can use the c_str() method of the string class to get a const char* with the string contents.
The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).
The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.
The c_str method of std::string returns a raw pointer to the memory buffer owned by the std::string .
You're right, your code is not valid since it uses an object whose lifetime has already ended. It works "by accident", you cannot rely on that.
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