[英]Coroutines: Do co_yielded string_views dangle?
我想混合 co_yielding 字符串文字和std::strings
Generator<std::string_view> range(int first, const int last) {
while (first < last) {
char ch = first++;
co_yield " | ";
co_yield std::string{ch, ch, ch};
}
}
但是,我想知道 std::string 的生命周期?
如果您知道您將立即使用string_view
可能是安全的?
for(auto sv : range(65, 91))
std::cout << sv;
https://godbolt.org/z/d5eoP9aTE
你可以像這樣讓它安全
Generator<std::string_view> range(int first, const int last) {
std::string result;
while (first < last) {
char ch = first++;
co_yield " | ";
result = std::string{ch, ch, ch};
co_yield result;
}
}
co_yield
是co_await
的奇特形式。 這兩個都是表達式。 因此,它們遵循表達規則。 表現為表達式求值的一部分的臨時變量將繼續存在,直到整個表達式完成。
co_await
表達式在協程恢復之前不會完成。 這很重要,因為您經常對純右值進行co_await
,因此如果您執行像co_await some_function()
這樣簡單的操作,則需要some_function
的返回值繼續存在,因為它的await_resume
function 需要能夠被調用。
如前所述, co_yield
只是co_await
的一種奇特形式。 所以規則仍然適用。 因此,您的生成器返回的任何string_view
對象都將指向恢復協程的調用之間的有效值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.