1
    // std::string_view vv("")
    // std::string ss = vv; // error
    // std::string ss(vv); // error
    std::string ss;
    ss = std::string_view(""); // ok, 'cause operator=(const StringViewLike&) is available

Is there a rational for this? Or is it just another thing that hasn't made into the standard yet?


The premise is false as is pointed out, that an explicit constructor exists.

Now I think the benifit is that the caller of a function should know copying happens to this std::string_view he's passing, while std::string(const char*) is often overlooked.

Eugene
  • 111
  • 4
  • 3
    There are two `std::string` [constructors](https://en.cppreference.com/w/cpp/string/basic_string/basic_string) that take a "StringViewLike" argument (see alternative 10 and 11 in the linked reference). – Some programmer dude Jun 15 '23 at 10:16
  • string_view has begin()/end() and std::string can be constructed from that. `template – Pepijn Kramer Jun 15 '23 at 10:19
  • 2
    By the way this is a nice example of type erasure. The std::string constructor is based on what the other class can do not what type is is. In this case provide a begin and end iterator. In the end it allows for more reusable (less coupled) code. The only thing you need to do is call the correct constructor explicitly. (Which is good, implicit conversions have their own issues) – Pepijn Kramer Jun 15 '23 at 10:30
  • @Someprogrammerdude My bad. I tried `std::string ss = vv` in my C++17 code base and assumed there was no constructor for that. – Eugene Jun 15 '23 at 11:13
  • Ah, that would use the alternative 10, which is marked as `explicit`, which explains the problem you have. :) – Some programmer dude Jun 15 '23 at 11:15
  • @Eljay I noticed this when I couldn't pass `std::string_view` to a `std::string` parameter, and I didn't know `std::string(const StringViewLike&) existed`. Now I guess simply passing `std::string(vv)` would do. – Eugene Jun 15 '23 at 11:16

0 Answers0