全局静态变量不是“保持定义”功能之外
问题描述:
我有一个程序,其中我定义的全局静态变量一旦离开我的“初始化函数”(不是构造函数)就不会保持初始化。下面是程序:全局静态变量不是“保持定义”功能之外
type.h
namespace type
{
static int * specialInt;
}
type.cpp
#include "type.h"
(这是有意留为空)
Branch.h
#include "type.h"
namespace type
{
bool initInt();
}
Branch.cpp
#include "Branch.h"
#include <iostream>
namespace type
{
bool initInt()
{
specialInt = new int;
*specialInt = 95;
std::cout << "Address from initInt(): " << specialInt << std::endl;
return true;
}
}
Leaf.h
#include "Branch.h"
#include <iostream>
namespace type
{
void PrintInt();
}
Leaf.cpp
#include "Leaf.h"
namespace type
{
void PrintInt()
{
std::cout << "Address: " << specialInt << std::endl;
std::cout << "Value: " << *specialInt << std::endl;
}
}
main.cpp中
#include "Leaf.h"
int main()
{
type::initInt();
type::PrintInt();
return 0;
}
的输出是从initInt()
地址:007F5910
地址:00000000
它崩溃之前。我读到关键字static
让变量有外部链接,所以为什么这会失败?为什么变量在initInt()
之外变得不确定?
答
namespace type
{
static int * specialInt;
}
这是一个静态整数指针的定义。 static
在名称空间范围内请求内部链接:包括type.h
的每个翻译单元都获得其自己的独立版本specialInt
。然后,当然,对specialInt
之一所做的更改不会影响其他的。
你婉做什么是声明变量在type.h
:
namespace type
{
extern int * specialInt;
}
...并在翻译单位之一提供一个单一的定义:
#include "type.h"
int *type::specialInt;
该定义将然后由所有人通过type.h
找到并使用。
答
我读关键字
static
允许变量具有外部连接,
否,当static使用具有在名字空间域中的对象时,它指定内部连接。这意味着,在Branch.cpp
中指定的specialInt
和在Leaf.cpp
中打印的specialInt
不是同一个对象。
3)...当在名称空间范围的声明中使用时,它指定 内部链接。