I have a C++ object (boost::format
) that has a str()
function which returns an std::string
.
So when I need a formatted C string, I need to write something like:
(boost::format("%1% %2%") % "1" % "2").str().c_str()
I find that rather verbose, and I need it a lot. I thought of creating a derived class which has an operator char*
and would work like this (Ch = char or wchar_t):
operator Ch const* () const
{
return str().c_str();
}
But of course, the string returned by str()
is deallocated when the function returns, and no valid C string is returned.
Is there any kind of workaround?
The workaround needs to create a string that exists as long as the surrounding function call:
lib_function((boost::format("%1% %2%") % "1" % "2").str().c_str());
// can be deallocated here