![](/img/trans.png)
[英]How to correctly create std::string from a std::string_view?
[英]Creating a std::string from std::string_view
給定一個string_view sv
和一個string s(sv)
, s
是否在內部使用與sv
相同的字符數組? 可以肯定地說當s
被銷毀時, sv
仍然有效嗎?
創建std::string
object總是復制(或移動,如果可以的話)字符串,並在內部處理它自己的 memory。
對於您的示例,由sv
和s
處理的字符串是完全不同且獨立的。
只需運行這個演示程序。
#include <iostream>
#include <string>
#inc,lude <string_view>
int main()
{
const char *s = "Hello World!";
std::cout << "The address of the string literal is "
<< static_cast< const void * >( s ) << '\n';
std::string_view sv( s );
std::cout << "The address of the object of the type std::string_view is "
<< static_cast< const void * >( sv.data() ) << '\n';
std::string ss( sv );
std::cout << "The address of the string is "
<< static_cast< const void * >( ss.data() ) << '\n';
}
它的 output 可能看起來像
The address of the string literal is 00694E6C
The address of the object of the type std::string_view is 00694E6C
The address of the string is 0133F7C0
可以看到,字符串文字的地址與std::string_view
的 object 的數據成員data
返回的 memory 的地址相同。
那就是 class std::string_view
只是對帶下划線的引用 object 的包裝。
至於 class std::string
,它會創建一個通常存儲在分配的 memory 中的字符串副本。
例如,您可能不會更改std::string_view
類型的 object,但std::string
是專門為處理存儲的字符串而設計的。
class名稱std::string_view
中的后綴view
表示只能查看std::string_view
類型的object所指的帶下划線的object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.