内存中的静态成员和静态全局变量
问题描述:
让我们考虑两种情况:内存中的静态成员和静态全局变量
1.)静态全局变量。 当我生成映射文件时,我无法在.bss或.data节中找到静态全局变量。
2.)静态成员
#include <stdio.h>
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
class Tree {
struct Node {
Node(int i, int d): id(i), dist(d) {}
int id;
int dist; // distance to the parent node
list<Node*> children;
};
class FindNode {
static Node* match;
int id;
public:
FindNode(int i): id(i) {}
Node* get_match()
{
return match;
}
bool operator()(Node* node)
{
if (node->id == id) {
match = node;
return true;
}
if (find_if(node->children.begin(), node->children.end(), FindNode(id)) != node->children.end()) {
return true;
}
return false;
}
};
Node* root;
void rebuild_hash();
void build_hash(Node* node, Node* parent = 0);
vector<int> plain;
vector<int> plain_pos;
vector<int> root_dist;
bool hash_valid; // indicates that three vectors above are valid
int ncount;
public:
Tree(): root(0), ncount(1) {}
void add(int from, int to, int d);
int get_dist(int n1, int n2);
};
Tree::Node* Tree::FindNode::match = 0;
...
可变树:: FindNode ::匹配是FindNode类的静态成员。这个变量在bss部分的map文件中提供。为什么这样??
*(.bss)
.bss 0x00408000 0x80 C:\Users\Администратор\Desktop\яндекс\runs\runs\\000093.obj
0x00408000 _argc
0x00408004 _argv
0x00408020 Tree::FindNode::match
我用MinGW的,操作系统Windows 7取得的所有目标文件G ++ ...... CPP -o ... OBJ命令,通过LD获取的地图文件.... OBJ -Map ..... map命令
答
全局变量已经在静态内存中,因此C重新使用现有关键字static
来创建一个全局变量“file-scoped”,并且C++遵循该套件。关键字static
从地图文件中隐藏您的全局。
另一方面,静态成员是类范围的,因此它们需要在映射文件中可用:其他模块需要能够访问类的静态成员(成员函数和成员变量)即使它们是分开编译的。
谢谢。还有一个问题, - 我怎么才能区分地图文件中的静态变量和全局变量,这有可能吗? – 2012-08-12 21:58:43
@AlexHoppus C风格的静态变量被排除在地图文件之外,所以如果你在地图文件中看到一个变量,并且它的名字中没有'::',它就是一个C风格的全局变量;如果它有'::',它是一个类的静态成员。 – dasblinkenlight 2012-08-12 22:02:57
是的,但如果它是包含在名称空间中的全局变量? namespace :: variable_name – 2012-08-12 22:04:50