C ++核心指南中的stack_array

时间:2017-02-01 11:35:35

标签: 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.
    // ...
}

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

3 个答案:

答案 0 :(得分:5)

据我所知,modalService.showModal({}, modalOptions) .then( function (result) { //custom actions for Yes button here }, function (result) { //custom actions for No button here } ); 是对使用标准C ++(截至当前标准)无法实现的假设类的建议。它的实现需要(目前)非标准的编译器特定支持,我怀疑这种非标准支持是否存在。

最接近的是一个宏,它包含对stack_array的调用(非标准功能,许多编译器都支持)。请参阅roalz的答案,获取具体实施的链接。我不确定这种方法是否可以达到VLA无法实现的任何安全性(许多编译器支持的另一个非标准功能) - 这并不是说VLA可以安全使用。

答案 1 :(得分:2)

刚刚在网上搜索过,我在这里找到了一个可能的(有些旧的)实现:
https://tlzprgmr.wordpress.com/2008/04/02/c-how-to-create-variable-length-arrays-on-the-stack/
它显然使用alloca()和预处理器宏(如建议并通过其他注释和答案确认)。

答案 2 :(得分:2)

截至2016年11月,Microsoft GSL实现仍然对提供stack_array的实现感兴趣:https://github.com/Microsoft/GSL/issues/348#issuecomment-260241339

另请参阅https://github.com/isocpp/CppCoreGuidelines/issues/347,特别是https://github.com/Microsoft/GSL/issues/134,其中谈到了为什么不容易。