Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning string::c_str() to a const char* when the string goes out of scope

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
like image 400
Abruzzo Forte e Gentile Avatar asked Nov 14 '11 10:11

Abruzzo Forte e Gentile


People also ask

Can I assign a string in a const char *?

You can use the c_str() method of the string class to get a const char* with the string contents.

How does c_str () work?

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).

What is the purpose of the c_str () member function of std :: 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.

What does string c_str return?

The c_str method of std::string returns a raw pointer to the memory buffer owned by the std::string .


1 Answers

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.

like image 114
Mat Avatar answered Oct 12 '22 23:10

Mat