C++ Logo


Advanced search

Named return values revival

From: Phil Bouchard <boost_at_[hidden]>
Date: Sun, 28 Mar 2021 17:00:15 -0400
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.


*Phil Bouchard*
Founder & CTO
C.: (819) 328-4743
Fornux Logo <http://www.fornux.com>

Received on 2021-03-28 16:00:22