Around 20 years ago the GCC compiler had what was called "named return values". It got taken away because compiler optimizations could generate equivalent code.
But I just found one case where this can't be true and I wanted to share my workaround with the community for potential discussion. Suppose you have a std::wstring wrapper:
#include <string>
namespace personal
{
struct string : std::wstring
{
typedef std::string base;
[...]
wchar_t const * get(std::wstring && r =
std::wstring())
{
r = std::wstring(base::begin(), base::end());
return r.c_str();
}
};
}
personal::string s = "Hello world";
cout << s.get() << endl; // will be just fine
In the aforementioned case, I am creating the return value before the function get() is called; this way the returned c_str() will live during the duration of the temporary variable created thus will not get destroyed within the function.
Anyway I just thought this might be useful to know.
Regards,