简体   繁体   English

协程:co_yielded string_views 是否悬空?

[英]Coroutines: Do co_yielded string_views dangle?

I want to mix up the co_yielding string literals and std::strings我想混合 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};
    }
}

However, I'm wondering about the lifetime of the std::string?但是,我想知道 std::string 的生命周期?

Maybe it's safe if you know you are going to consume the string_view immediately?如果您知道您将立即使用string_view可能是安全的?

for(auto sv : range(65, 91))
   std::cout << sv;

https://godbolt.org/z/d5eoP9aTE https://godbolt.org/z/d5eoP9aTE

You could make it safe like this你可以像这样让它安全

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 is a fancy form of co_await . co_yieldco_await的奇特形式。 Both of these are expressions.这两个都是表达式。 And therefore, they follow the rules of expressions.因此,它们遵循表达规则。 Temporaries manifested as part of the evaluation of the expression will continue to exist until the completion of the entire expression.表现为表达式求值的一部分的临时变量将继续存在,直到整个表达式完成。

co_await expressions do not complete until after the coroutine resumes. co_await表达式在协程恢复之前不会完成 This is important, as you often co_await on prvalues, so if you do something as simple as co_await some_function() , you need the return value of some_function to continue to exist, as its await_resume function needs to be able to be called.这很重要,因为您经常对纯右值进行co_await ,因此如果您执行像co_await some_function()这样简单的操作,则需要some_function的返回值继续存在,因为它的await_resume function 需要能够被调用。

As previously stated, co_yield is just a fancy form of co_await .如前所述, co_yield只是co_await的一种奇特形式。 So the rules still apply.所以规则仍然适用。 So any string_view objects returned by your generator will point to valid values between calls to resume the coroutine.因此,您的生成器返回的任何string_view对象都将指向恢复协程的调用之间的有效值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM