Is there a problem stringstream.str (). c_str ()?

For code:

stringstream ss("012345678901234567890123456789012345678901234567890123456789");  

Some articles indicate that this is not true for later use because of the temps object temp return temp and will be destroyed before calling .c_str ();

 const char* cstr2 = ss.str().c_str();  

but I am running an example, no problem? how to understand?

+1
source share
3 answers

But I ran an example, no problem?

Actually there is nothing wrong with the expression:

const char* cstr2 = ss.str().c_str();

The temporary object (copy) returned ss.str()will live long enough so you can get the base c-string with c_str().

Of course, by the end of the expression, you will have a pointer const charto the object, which is probably freed (this is highly implementation dependent std::basic_string).

, , . :

auto x = ss.str();
const char* cstr2 = x.c_str(); 

- , str() / , x.c_str() .

+6

, , - . "" , .

-, , , . stringstream , std::stringstream::str() (.. ), - , , C-.

+4

++.

, ( C), () , , .

str() .

. - (, string& s = ss.str()), , .

c_str(), , . .

, , c_str , , - C:

const char * cstr2;
{
    char ss_str[100];            // str() return value is dynamically created
    char * c_str = &ss_str_[10]; // c_str() takes a reference to some part of it
    cstr2 = c_str;               // cstr2 takes an indirect reference to str() ret. val.
}                                // compiler pulls the plug on str() ret. val.

, c_str str().

Now, since temporary objects are allocated on the stack, you may never notice the problem. Selecting an object in itself will most likely not change the value of a nonexistent string value, but as soon as the compiler reuses this bit of the stack, the proverbial guru will have something to meditate on.

+2
source

Source: https://habr.com/ru/post/1653760/


All Articles