mardi 11 mai 2021

Problem with a parsing function (int to const char*)

I needed to create a parsing function so i wrote this:

inline const char* parse(const int &arg)
{
     return std::to_string(arg).c_str();
}

Looks pretty rational - at least to me - but when i try to see the value of this function with std::cout instead of an integer value i get some random ascii characters.

So i tried changing the function and i ended up with something like this:

inline const char* parse(const int &arg)
{
     return (new std::string(std::to_string(arg)))->c_str();
}

And it works as intended, but what I would like to know is why the first case of function doesn't work properly.

Also, there's a secondary question that has arisen (probably a stupid one as im a beginner) - should I return the value of the function with std::move if i create the std::string dynamically? return std::move((new std::string(std::to_string(arg)))->c_str());

Aucun commentaire:

Enregistrer un commentaire