8
void Foo1(string_view view) {
... 
}

string str = "one two three";

Foo1("one two three"); // Implicitly convert char* to string_view

Foo1(str); 

enter image description here I wonder which constructor converts char* to string_view implicitly and which one converts the string to string_view implicitly?

I know constructor (4) convert const char* to string_view but what I passed is char*.

1
  • Even if you had actually passed char* as you claim, any pointer-to-mutable is usable as a pointer-to-const (you can substitute reference for pointer there and that's also true). The const there is a promise that the string view will not write to the pointed-to characters. Commented Jun 10, 2024 at 7:52

3 Answers 3

17

std::string_view has a non-explicit converting constructor taking const char*, which supports implicit conversion from const char* to std::string_view.

constexpr basic_string_view(const CharT* s);

When you say:

but what I passed is char*.

You're actually passing a string literal (i.e. "one two three"), whose type is const char[14] (including the null terminator '\0'), which could decay to const char*.

And std::string has a non-explicit conversion operator which supports implicit conversion from std::string to std::string_view.

constexpr operator std::basic_string_view<CharT, Traits>() const noexcept;

Sign up to request clarification or add additional context in comments.

2 Comments

What makes the conversion operator special so that string to string_view is implicit? I notice basic_string also has c_str() function but that does not make string to char* implicit?
@echoLee std::string defines a conversion operator to std::string_view, and it is implicit simply by virtue of the fact that it is not declared as explicit. std::string::c_str() is not a conversion operator, just a plain method. std::string does not define any conversion operator to char*, neither implicit nor explicit.
0

It's https://en.cppreference.com/w/cpp/string/basic_string/operator_basic_string_view: basic_string::operator basic_string_view()

together with string_view's copy constructor (2)

Comments

0

Below is how it convert from std::basic_string to std::basic_string_view.

Copy from gcc-13.2.0/libstdc++-v3/include/bits/basic_string.h

   /**
   *  @brief  Convert to a string_view.
   *  @return A string_view.
   */
  _GLIBCXX20_CONSTEXPR
  operator __sv_type() const noexcept
  { return __sv_type(data(), size()); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.