15

还有一个static问题。我已阅读以下内容:

而且我仍然无法理解以下行为:我有一个h文件:

// StaticTest.h
#include <stdio.h>

static int counter = 0;

struct A {
    A () {
        counter++;
        printf("In A's ctor(%d)\n", counter);
    }
    ~A () {
        counter--;
        printf("In A's dtor(%d)\n", counter);
    }
};

static A a;

还有两个cpp文件:

// StaticTest1.cpp
#include "StaticTest.h"

int main () {
 return 0;
}

和:

// StaticTest2.cpp
#include "StaticTest.h"

程序的输出是:

In A's ctor(1)
In A's ctor(2)
In A's dtor(1)
In A's dtor(0)

现在,A的构造函数被调用了两次,因为h文件被包含了两次,并且由于声明了A名为的实例,它具有内部链接并且编译器很高兴。由于它也被声明为静态,它也具有内部链接,我希望它的值不会在两个文件中共享 --- 但程序输出暗示该值是共享的,因为它最多为 2。astaticcountercpp

有什么见解吗?

h编辑:在vs.文件中声明静态变量的上下文中,关于什么被认为是“良好的编程习惯”的任何答案cpp也受到欢迎。

4

1 回答 1

13

If StaticTest.h is shared between difference source files then you will get undefined behaviour.

If you define a class or inline functions in different translation units then their definitions must be the same (same sequence of tokens) and, crucially, any identifiers must refer to the same entity (unless a const object with internal linkage) as in the definition in another translation unit.

You violate this because counter has internal linkage so in different translation units the identifier in the function definitions refers to a different object.

Reference: C++03 3.2 [basic.def.odr] / 5.

于 2010-11-25T12:09:07.877 回答