繁体   English   中英

确保我们初始化每个变量一次且仅一次

[英]Ensure that we initialize each variable once and only once

下面是来自 LLVM 的异常处理库 libcxxabi 的测试(顺便说一下,它使用了 LLVM 的堆栈展开库 libunwind):

// libcxxabi\test\test_guard.pass.cpp
...
// Ensure that we initialize each variable once and only once.
namespace test1 {
    static int run_count = 0;
    int increment() {
        ++run_count;
        return 0;
    }
    void helper() {
        static int a = increment();
        ((void)a);
    }
    void test() {
        static int a = increment(); ((void)a);
        assert(run_count == 1);
        static int b = increment(); ((void)b);
        assert(run_count == 2);
        helper();
        assert(run_count == 3);
        helper();
        assert(run_count == 3);
    }
}

...

int main()
{
    test1::test();
}

也许我遗漏了一些明显的东西,但我不确定这个测试背后的想法是什么(它测试什么以及如何测试)。 你有什么想法?

为什么这三个变量

static int run_count
static int a (in test(), not in helper())
static int b 

声明为静态?

这是一个确保编译器正常工作的测试。 它应该传递任何确认的 C++ 编译器。

我猜这是一个快速的健全性检查,会有更深入的测试,这可能更难理解为什么他们在有缺陷的编译器上失败。

变量被声明为静态以确保各种形式的静态变量被正确初始化,并且初始化器只被调用一次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM