简体   繁体   English

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

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

Below is a test from LLVM's exception handling library libcxxabi (which by the way uses LLVM's stack unwind library libunwind):下面是来自 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();
}

Maybe I'm missing something obvious but I'm not sure what's the idea behind this test (what does it test and how).也许我遗漏了一些明显的东西,但我不确定这个测试背后的想法是什么(它测试什么以及如何测试)。 Do you have any ideas?你有什么想法?

Why are these three variables为什么这三个变量

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

declared to be static?声明为静态?

It's a test to ensure that the compiler works correctly.这是一个确保编译器正常工作的测试。 It should pass on any confirming c++ compiler.它应该传递任何确认的 C++ 编译器。

I'd guess it's there as a quick sanity check, there will be more in-depth tests which might be harder to understand why by they are failing on a buggy compiler.我猜这是一个快速的健全性检查,会有更深入的测试,这可能更难理解为什么他们在有缺陷的编译器上失败。

The variables are declared static to ensure the various forms of static variables are initialised correctly and that the initialisers are only called once.变量被声明为静态以确保各种形式的静态变量被正确初始化,并且初始化器只被调用一次。

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

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