[英]Is there really no explicit constructor of std::string from an std::string_view?
一些(很多?)同時std::string_view
和std::string
的程序員會問自己:“為什么我可以將后者轉換為前者,而反過來卻不行?”
問題的一部分在這里得到了回答:
為什么沒有從 std::string_view 到 std::string 的隱式轉換?
一個人可以喜歡或不喜歡的原因。 但是 -顯式構造函數呢? 我在 cppreference.com 的std::string
構造函數頁面上沒有看到一個?
關於隱式構造函數的問題的兩個答案基本上是 state,隱式構造函數會導致 memory 分配和 memory 副本,這不清楚程序員的願望。 好的,好吧,使用顯式構造函數 - 程序員確實想要分配和復制。 為什么不給他/她呢?
正如@Barry 和@StoryTeller 所指出的,這個構造函數實際上是存在的——盡管是通過使用模板; 您只是沒有注意到您鏈接到的 cppreference 頁面上的“細則”:
template < class T >
explicit constexpr basic_string(
const T& t,
const Allocator& alloc = Allocator()
);
這將從std::string_view
構造一個std::string
。 為什么? 因為它是什么:
隱式將
t
轉換為字符串視圖sv
,就好像通過std::basic_string_view<CharT, Traits> sv = t;
,然后用sv
的內容初始化字符串,就像通過std::basic_string(sv.data(), sv.size(), alloc)
。
對於T = std::string_view
的特定情況:
template <>
explicit constexpr basic_string<std::string_view>(
const std::string_view& t,
const Allocator& alloc = Allocator()
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.