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



以下是LLVM异常处理库libcxxabi的测试(顺便说一句,它使用LLVM的堆栈Undind Librard libunwind):

// libcxxabitesttest_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 编译器。

我猜它是作为快速的理智检查,将会有更多深入的测试,这可能会更难理解为什么它们在越野编译器上失败。

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

最新更新