c++ - 内存中的静态成员和静态全局变量

标签 c++ global-variables static-variables

让我们考虑两种情况:

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;
...

变量 Tree::FindNode::match 是 FindNode 类的静态成员。这个变量出现在 bss 部分的映射文件中。为什么这样??

 *(.bss)
 .bss           0x00408000       0x80 C:\Users\Администратор\Desktop\яндекс\runs\runs\\000093.obj
                0x00408000                _argc
                0x00408004                _argv
                0x00408020                Tree::FindNode::match

我用的是MinGW,os windows 7。所有的目标文件都是通过g++ ...cpp -o ...obj命令得到的,map文件是通过ld ....obj -Map .....map命令得到的

最佳答案

全局变量已经在静态内存中,所以 C 重新使用了现有的关键字 static 来使全局变量“文件作用域”,C++ 也效仿了这一套件。关键字 static 从 map 文件中隐藏您的全局。

另一方面,静态成员是类作用域的,因此它们需要在映射文件中可用:其他模块需要能够访问类的静态成员,包括成员函数和成员变量,甚至如果它们是单独编译的。

关于c++ - 内存中的静态成员和静态全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926115/

相关文章:

python - Multiprocessing.Manager() 全局变量的奇怪行为

python - 静态变量中使用的理解看不到局部函数?

c++ - 内联变量被多次初始化

c++ - 使用异步调用模板函数

c++ - 为删除的对象赋值

c++11 - 链接错误 : multiple definition of static variable

java - getClass()方法可以用来访问静态变量吗?

C++:调用多个类的相同函数

c - 全局变量输出不正确

c++ - DLL 的全局变量存储在内存中的什么位置?