Example of the perils of binding rvalues to const ref

Szymon Gatner via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 17 02:01:42 PDT 2014


On Wednesday, 17 September 2014 at 08:57:36 UTC, Szymon Gatner 
wrote:
> On Wednesday, 17 September 2014 at 08:52:58 UTC, Arjan wrote:
>> 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
>>
>> Forgive me my ignorance but  get_url() returns a std::string 
>> (on the stack), so its address can be token.
>> And iirc the explainer Scott Meyers explained once "iff you 
>> can take its address its not a rvalue its a lvalue". So isn't 
>> the get_scheme_from_url() not simply holding a const ref to 
>> temporary? (which most compiler warn about)
>>
>> ...Or am I missing the point?
>>
>>> reference to const and implicitly passed to string_view's 
>>> constructor. The obtained view refers to a dead string.
>>>
>>>
>>> Andrei


[ Sorry for double posting, i must have double clicked on "reply" 
button accidentally. ]

std::string returned from get_url() is a temporary and hence a 
"rvalue". In fact it's address cannot be taken. It is often 
helpful to think of lvalues as things that can appear on the left 
side of assignment expression.


More information about the Digitalmars-d mailing list