C++静态成员函数中静态变量的作用域

C++ Scope of Static Variable In a Static Member Function

本文关键字:变量 作用域 静态 静态成员 函数 C++      更新时间:2023-10-16

我有一个简单的对象可以进行一些解析。在里面,有一个parse函数,包含一个静态变量,用于限制打印给用户的错误消息数量:

struct CMYParsePrimitive {
    static bool Parse(const std::string &s_line)
    {
        // do the parsing
        static bool b_warned = false;
        if(!b_warned) {
            b_warned = true;
            std::cerr << "error: token XYZ is deprecated" << std::endl;
        }
        // print a warning about using this token (only once)
        return true;
    }
};

现在,这些解析原语在类型列表中传递给解析器专用化。还有一些其他接口告诉解析器应该使用哪些解析原语来解析哪些令牌类型。

我的问题是每次应用程序运行最多应该显示一次警告。但就我而言,它有时会显示多次,似乎是每个解析器实例而不是应用程序实例。

我正在使用Visual Studio 2008,我想这可能是一些错误或偏离标准?有谁知道为什么会这样?

我没有注意到该函数也是一个模板。我的坏。它在代码中使用不同的参数实例化两次 - 因此警告有时会打印两次。真正的代码看起来更像这样:

struct CMYParsePrimitive {
    template <class CSink>
    static bool Parse(const std::string &s_line, CSink &sink)
    {
        // do the parsing, results passed down to "sink"
        static bool b_warned = false;
        if(!b_warned) {
            b_warned = true;
            std::cerr << "error: token XYZ is deprecated" << std::endl;
        }
        // print a warning about using this token (only once)
        return true;
    }
};

所以有例如 CMYParsePrimitive::Parse<PreviewParser>::b_warned,它可以在PreviewParser使用时打印一次警告,然后也可以CMYParsePrimitive::Parse<Parser>::b_warnedParser使用时打印警告。