mardi 16 juin 2020

Will using c_str on a temp still fail when returned as QString?

I know about dangling pointers when using c_str wrongly. like this:

const char* str_ptr = functionReturningString().c_str();
// str_ptr is invalid, as the returned string from the function was temporary, and c_str simply points to that array.

I would like to know if this still applies to this code (C++11, Qt 5.5)

 QString UUId::toString () const
 {
    return to_string (_uuid).c_str();
 }

This is using the to_string function from boosts uuid class.

it returns a std::string. This is a temporary object, and I expect c_str() to be dangerous.

Does the return type QString change this somehow? I am not sure if that will actually mean:

return QString(to_string (_uuid).c_str()); (I'm just guessing)

which should create a copy (if you look at QString (const char *) constructor) if I'm not mistaking.

Question: Is it safe? Or is the temp destroyed before the QString is constructed?

Aucun commentaire:

Enregistrer un commentaire