如果我返回本地协程变量的地址,例如通过承诺,它是否保证按 C++ 标准工作?考虑一个例子(基于https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html):
#include <coroutine>
#include <iostream>
struct ReturnObject {
struct promise_type {
unsigned * value_ = nullptr;
void return_void() {}
ReturnObject get_return_object() {
return {
.h_ = std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void unhandled_exception() {}
};
std::coroutine_handle<promise_type> h_;
operator auto() const { return h_; }
};
template<typename PromiseType>
struct GetPromise {
PromiseType *p_;
bool await_ready() { return false; }
bool await_suspend(std::coroutine_handle<PromiseType> h) {
p_ = &h.promise();
return false;
}
PromiseType *await_resume() { return p_; }
};
ReturnObject counter()
{
auto pp = co_await GetPromise<ReturnObject::promise_type>{};
for (unsigned i = 0;; ++i) {
pp->value_ = &i; // is it legal?
co_await std::suspend_always{};
}
}
int main()
{
std::coroutine_handle<ReturnObject::promise_type> h = counter();
auto &promise = h.promise();
for (int i = 0; i < 5; ++i) {
std::cout << "counter: " << *promise.value_ << std::endl;
h();
}
h.destroy();
}
https://gcc.godbolt.org/z/P5PMc15qW
在实践中我看到它确实有效,但它真的合法吗?
是的,这是合法的。的局部变量counter
存储在拥有的动态分配的对象中h
。
释放后使用可能性的常见警告就在那里,即promise
在 之后悬挂h.destroy()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句