在 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 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 C++20 中删除协程的复制/移动函数并实例化它是否合法?

在C ++ 11中返回本地值的最佳方法

如何在C ++中返回本地创建的对象?

在协程 lambda (C++) 中捕获 `this` 是否安全

libmysql:警告:返回了本地变量“行”的地址(C ++ / C)

C:返回本地结构有效但返回本地数组不?

C ++ 20中的协程是什么?

返回C中静态const变量的地址

如何返回依赖于方法中启动的协程结果的值?(C#)

函数返回本地变量[-Wreturn-local-addr]的地址

无栈C ++ 20协程是否有问题?

如何检测 C++20 协程中的堆栈展开?

如何在C中的for循环内实现协程

如何在循环 C# 中中断等待协程?

Clang 中 C++20 协程支持的状态如何?

为什么Python函数可以返回本地声明的数组,但是C无法返回?

在C中while(* pointer)是否合法?

在C中的结构初始化程序中使用变量是否合法?

C-避免出现警告“与本地变量相关联的堆栈内存地址返回”

为什么在返回本地std :: stringstream时c ++不使用RVO?

从Bash变量返回本地值?

GetObjectField() 是否返回本地引用?

当我们返回本地地址而不返回本地变量时,为什么会产生运行时错误?

堆栈变量的C返回地址= NULL?

C ++ 20协程,std返回类型和状态持久性

C ++协程:从最后的挂起点调用`handle.destroy`是否有效?

返回本地参考与参考返回功能的本地变量

将C与C ++链接是否可以避免在C中合法但在C ++中合法的未定义行为?

在函数中返回本地结构