大佬教程收集整理的这篇文章主要介绍了在 C++ 中返回本地协程变量的地址是否合法?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我返回一个本地协程变量的地址,例如通过承诺,它是否保证按 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 @R_197_11372@se; }
bool await_suspend(std::coroutIne_handle<PromiseType> h) {
p_ = &h.promise();
return @R_197_11372@se;
}
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()
之后。
它在某些情况下可以工作,但这不是编写程序的好方法。指针指向的内存单元可以(并且可能很快)被其他变量覆盖。尝试在循环之前编写一些代码(声明一些变量)并再次检查结果。
以上是大佬教程为你收集整理的在 C++ 中返回本地协程变量的地址是否合法?全部内容,希望文章能够帮你解决在 C++ 中返回本地协程变量的地址是否合法?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。