1. 簡介
C++17之后才有string_view
,主要為了解決C語言常量字符串在std::string
中的拷貝問題。
即readonly
的string
。
2. 引入
2.1 隱式拷貝問題
將C常量字符串拷貝了一次
#include <iostream>
#include <string>int main()
{std::string s{ "Hello, world!" }; std::cout << s << '\n';return 0;
}
下面的程序拷貝了兩次, 當然可以直接使用const std::string &str
#include <iostream>
#include <string>void printString(std::string str) // str makes a copy of its initializer
{std::cout << str << '\n';
}int main()
{std::string s{ "Hello, world!" }; // s makes a copy of its initializerprintString(s);return 0;
}
2.2 解決
對于只讀的常量字符串直接聲明為string_view
類型
#include <iostream>
#include <string_view>// str provides read-only access to whatever argument is passed in
void printSV(std::string_view str) // now a std::string_view
{std::cout << str << '\n';
}int main()
{std::string_view s{ "Hello, world!" }; // now a std::string_viewprintSV(s);return 0;
}
3. Ref
learn_cpp