簡體   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