Example of the perils of binding rvalues to const ref

monarch_dodra via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 16 11:26:36 PDT 2014


On Tuesday, 16 September 2014 at 15:30:49 UTC, Andrei 
Alexandrescu wrote:
> http://www.slideshare.net/yandex/rust-c
>
> C++ code:
>
> std::string get_url() {
>     return "http://yandex.ru";
> }
>
> string_view get_scheme_from_url(string_view url) {
>     unsigned colon = url.find(':');
>     return url.substr(0, colon);
> }
>
> int main() {
>     auto scheme = get_scheme_from_url(get_url());
>     std::cout << scheme << "\n";
>     return 0;
> }
>
> string_view has an implicit constructor from const string& (see 
> "basic_string_view(const basic_string<charT, traits, 
> Allocator>& str) noexcept;" in 
> https://isocpp.org/files/papers/N3762.html). The function 
> get_url() returns an rvalue, which in turn gets bound to a 
> reference to const and implicitly passed to string_view's 
> constructor. The obtained view refers to a dead string.
>
>
> Andrei

Arguably, the issue is not const ref binding to an rvalue itself, 
but rather taking (and *holding*) the address of a parameter that 
is passed by const ref. If you want to *hold* that reference, it 
should be explicitly passed by pointer. That and having the whole 
thing neatly packaged in an implicit constructor. If you are 
doing something that dangerous, at the very least, make it 
explicit.

I mean, the example might as well just be:

std::string_view get_scheme()
{
     std::string myString = get_url();
     return myString; //Boom
}

Exact same undefined result, without binding to rvalues.

I prefered your smoking gun of:

const int& a = max(1, 2);

But again, the part of the issue here is the passing of 
references.

If we made "auto ref" to mean "pass either an existing object, or 
binds to an rvalue (at call site, not via template overload)" and 
in the implementation, made the passed in argument "considered a 
local variable as if passed by value you may not escape", then 
I'm pretty sure we can have our cake and eat it. Proper escape 
analysis would help too.


More information about the Digitalmars-d mailing list