vendredi 29 janvier 2016

How does experimental::basic_string_view<> work?

I am not 100% that the following code is semantically correct:

#include <iostream>
#include <experimental/string_view>

int main()
{
    std::string str = "lvalue string";

    std::experimental::string_view view_lvalue(str);
    std::experimental::string_view view_rvalue(std::string{"rvalue string"});

    std::cout << view_lvalue << '\n' << view_rvalue << '\n';
}

Live on Wandbox

Question: Can I legally bind a rvalue to such a view, or is it just UB? If yes, how does it work? As far as I know, a rvalue does not bind to a const reference (which I assume the view holds to the original string) via the constructor, so I thought that at the end of the statement std::experimental::string_view view_rvalue(std::string{"rvalue string"}); the reference will be dangling. Does string_view use a more sophisticated approach?

I am asking this because I am trying to write a similar view for some matrix class, and don't yet know how to deal with rvalues (I can disable them of course, but I don't think it's the best approach).

Aucun commentaire:

Enregistrer un commentaire