作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
GCC C++ 编译器(以及许多其他 C++ 编译器)提供非标准扩展,例如
alloca()
用于基于堆栈的分配 最佳答案
不幸的是,alloca
与 GCC 中的 C++20 协程不兼容。最糟糕的是编译器没有警告它。
此代码示例演示了不兼容性:
#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>{};
//unsigned a[1]; auto & i = a[0]; //this version works fine
auto & i = *new (alloca(sizeof(unsigned))) unsigned(0); //and this not
for (;; ++i) {
pp->value_ = &i;
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 << *promise.value_ << std::endl;
h();
}
h.destroy();
}
https://gcc.godbolt.org/z/8zG446Esx
0 1 2 3 4
,但不完全是由于
alloca
的用法
关于c++ - 我们可以在 c++20 协程中使用 alloca() 或可变长度数组扩展吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67576168/
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!