string_view behaviour when passing temporary std::string

前端 未结 1 1728
遇见更好的自我
遇见更好的自我 2021-01-11 17:53

I just ran into some misunderstanding: at least in libc++ implementation std::experimental::string_view has the following concise implementation:

template &l         


        
相关标签:
1条回答
  • 2021-01-11 18:15

    That's right. A string_view is a non-owning wrapper with reference semantics that must only be used when the referred string outlives the use of the view.

    The typical use case is in function parameters where the actual string lives for the duration of the function call and the function body never stores the view, but only reads it:

    void foo(std::experimental::string_view message)  // pass by value
    {
        std::cout << "You said, '" << message << "'.\n";
    }
    

    Usage:

    foo("Hello");       // OK, string literal has static storage
    foo(s);             // OK, s is alive
    foo(s.substr(1));   // OK, temporary lives until end of full-expression
    

    The moral is: If you only need the string for the duration of the function body, give the function a string_view parameter, and it can uniformly bind to any kind of stringoid argument. You don't need a function template, copying string_views is cheap, and you get some neat substringing operations for free. By contrast, never store a string_view, but always store astring:

    struct X
    {
        X(std::experimental::string_view s) : s_(s) {}
    
        std::string s_;     // NEVER have a string_view class member!
    };
    
    0 讨论(0)
提交回复
热议问题