Does a function local static variable automatically incur a branch?

前端 未结 2 2071
礼貌的吻别
礼貌的吻别 2021-02-18 13:05

For example:

int foo()
{
    static int i = 0;
    return i++;
}

The variable i will only be initialized to 0 the fir

2条回答
  •  Happy的楠姐
    2021-02-18 13:43

    Yes, it must incur a branch, and it must also incur at least an atomic operation for safe concurrent initialization. The Standard requires that they are initialized on function entry, in a concurrency-safe way.

    The implementation can only dodge this requirement if it can prove that the difference between lazy init and some earlier initialization like before main() is entered is equivalent. For example, simple PODs initialized from constants, the compiler may choose to initialize it earlier like a file-scope global since it's non-observable and saving the lazy initialization code, but that's a non-observable optimization.

提交回复
热议问题