Example of the perils of binding rvalues to const ref
Szymon Gatner via Digitalmars-d
digitalmars-d at puremagic.com
Wed Sep 17 01:57:35 PDT 2014
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
More information about the Digitalmars-d
mailing list