c++ - C++ 核心指南中的 stack_array

标签 c++ c++11

C++ 核心指南提到了一个叫做 stack_array 的东西。 .它的用法如下:

const int n = 7;
int m = 9;

void f()
{
    std::array<int, n> a1;
    stack_array<int> a2(m);  // A stack-allocated array.
                             // The number of elements are determined
                             // at construction and fixed thereafter.
    // ...
}

但是如何实现这样的类呢?我们如何在运行时动态确定堆栈大小?

最佳答案

据我所知,stack_array 是对无法使用标准 C++(按照当前标准)实现的假设类的建议。它的实现需要(当前)非标准编译器特定的支持,我怀疑这种非标准支持是否存在。

您可以获得的最接近的是一个宏,它包装了对 alloca 的调用(一种非标准功能,许多编译器都支持)。有关具体实现的链接,请参见 roalz 的答案。我不确定这种方法是否可以实现 VLA 无法实现的任何安全性(另一个非标准功能,许多编译器都支持)——这并不是说 VLA 可以安全使用。

关于c++ - C++ 核心指南中的 stack_array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978790/

相关文章:

c++ - 如何使用 -std=c++11 : ‘auto_ptr’ is deprecated 解决 g++ 警告

c++ - std::vector<T>::resize(n) vs reserve(n) with operator[]

C++ Variadic 模板 - 无法找出编译错误

c++ - 如何隐藏SHLD延迟?

c++ - Arduino 控制 ledstrip 与 neopixel 卡住

c++ - 为什么这个 noexcept 对性能如此重要,而类似的其他 noexcept 却没有?

c++ - 将 boost 图中的内部属性转换为 boost 图中的外部属性容器

c++ - 如何在 C++ 中格式化输出

c++ - xerces-c++ 编译/链接问题

C++ WINAPI 共享内存动态数组