Example of the perils of binding rvalues to const ref

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 16 08:31:25 PDT 2014


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


More information about the Digitalmars-d mailing list