C++ Logo

std-proposals

Advanced search

Re: Named return values revival

From: Magnus Fromreide <magfr_at_[hidden]>
Date: Mon, 29 Mar 2021 11:42:06 +0200
On Sun, Mar 28, 2021 at 11:18:51PM -0400, Phil Bouchard via Std-Proposals wrote:
>
> On 3/28/21 10:44 PM, Jason McKesson via Std-Proposals wrote:
> >
> > > As such, it is unclear what exactly you want to change about the
> > > language. It's also unclear why you would want to write code this way
> > > instead of just returning the string and letting the *user* call the
> > > function.
> > >
> > > What I have shown is one case of the need for the revival of the named return values, but using a workaround. For a proposal, the syntax could use what GCC was using:
> > >
> > > https://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_5.html#SEC106
> > As a general rule, if you're going to suggest something, you should
> > probably explain what it is, rather than just naming a term and
> > expecting people to Google it to find out what you actually want.
> Sorry I guess 20 years ago is not in everybody's curriculum.
> > In any case, it's not clear how what you described is equivalent to
> > what you want. In the GCC feature, the "named return value" is of a
> > type exactly equivalent to the return type. And thus, the object whose
> > lifetime will be extended based on the caller will be the return
> > value's type. But in your examples, the return value is a `char
> > const*`, not the string object that owns it. So it's not clear how
> > what you've asked for would solve the problem in your examples
> > *without* returning a prvalue string (and therefore requiring the user
> > to use `c_str`).
>
> Good point, I should have realized that. So I guess the old GCC's named
> return value is not powerful enough. Maybe the following syntax using square
> brackets could be used instead, this way the variable created before the
> call couldn't possibly be overridden by the user:
>
> #include <string>
>
> namespace personal
> {
> struct string : std::wstring
> {
>     typedef std::wstring base;
> [...]
>
>     char const * encoded_c_str() [std::string && r = std::string()]
>     {
>         r = std::string(base::begin(), base::end());
>
>         return r.c_str();
>     }
> };
> }
>
> personal::string s = "Hello world";
>
> cout << s.encoded_c_str() << endl; // will be just fine

In what way does that differ from

const char* encoded_c_str(std::string& r = std::string())
{
    r = std::string(base::begin(), base::end());
    return r.c_str();
}

(Yes, I am aware that this code rightfully will result in a warning from
 current compilers but it still looks suspiciosly similar to your proposal)

/MF

Received on 2021-03-29 04:42:19