簡體   English   中英

從 std::string_view 創建一個 std::string

[英]Creating a std::string from std::string_view

給定一個string_view sv和一個string s(sv)s是否在內部使用與sv相同的字符數組? 可以肯定地說當s被銷毀時, sv仍然有效嗎?

創建std::string object總是復制(或移動,如果可以的話)字符串,並在內部處理它自己的 memory。

對於您的示例,由svs處理的字符串是完全不同且獨立的。

只需運行這個演示程序。

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM