考虑下面这个简单的协程,它跟踪它的构造和销毁:
#include <coroutine>
#include <iostream>
struct simple {
static inline int x = 0;
int id = 0;
simple() : id{ x++ } { std::cout << id << " constructed\n"; }
simple(simple&&) : id{ x++ } { std::cout << id << " move constructed\n"; }
~simple() { std::cout << id << " destructed\n"; }
struct promise_type {
simple get_return_object() { return {}; }
void return_void() {}
void unhandled_exception() { std::terminate(); }
auto initial_suspend() noexcept { return std::suspend_never{}; }
auto final_suspend() noexcept { return std::suspend_never{}; }
};
};
simple f() { co_return; }
int main() {
f();
}使用GCC 10.1编译时,输出为:
0 constructed
1 move constructed
1 destructed-notably,id 0永远不会被销毁。这是真的,即使是在使用GCC树干的情况下。
我是不是做错了什么,隐藏的UB之类的?还是说这件事是GCC的错?
作为比较,我尝试使用Clang的实验性协程支持,并获得
0 constructed
0 destructed这更接近于我的预期。如果我注释掉协程对象中的move构造器,我也会得到这个“正确”的输出,即使在GCC中也是如此。
发布于 2020-06-03 17:25:09
正如Oliv提到的,这似乎只是一个错误,有了GCC的实验性协程支持。一张罚单已经被提出here。
https://stackoverflow.com/questions/62125871
复制相似问题