Why string_view instead of generalized container_view?

后端 未结 2 540
梦如初夏
梦如初夏 2021-01-08 00:33

I\'ve found string_view from new C++17 standard a bit redundant.

We\'ve got a quite verbose collection of simple mechanisms for passing data to callee, without much

2条回答
  •  悲哀的现实
    2021-01-08 00:49

    string_view offers more than a simple pointer on string. You need to look at it as more than a simple non-owning pointer: if that's all it were, string_view couldn't allow you to "slice" parts of the string, and apply operations to it (while still being a view; thus not incurring the cost of copy):

    char *s = "welcome to stackoverflow";
    auto s = std::string_view{s + 8, 2}; // a view on "to"
    // you can then apply many operations on this view, that wouldn't make sense more on your general non_owning:
    s.remove_prefix(std::min(s.find_first_not_of(" "), s.size()));
    // it also "inherits" (copies the API) a lot directly from std::basic_string
    auto view2 = s.substr(3, 4); // a generic non-owning ptr would copy here, instead of giving you a new view
    

提交回复
热议问题