C++静态成员函数中静态变量的作用域
C++ Scope of Static Variable In a Static Member Function
我有一个简单的对象可以进行一些解析。在里面,有一个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_warned
在Parser
使用时打印警告。
相关文章:
- 在类函数中初始化外部作用域变量
- 不同作用域中的静态变量和全局变量
- 未在此作用域中声明的函数和变量 (C++)
- 如何在C++中访问作用域的变量输出?
- 不同块作用域中的 C++ 变量具有相同的地址
- C++If语句变量作用域
- 派生类变量作用域 c++
- 如何理解C++变量作用域规则
- C/C++编译器关于变量作用域的优化
- 应用程序有2个静态变量作用域
- 堆变量作用域
- c++中变量作用域的机制
- c++变量作用域的类友
- 函数所需的总堆栈大小如何与变量作用域相关
- 声明友元函数时出现变量作用域错误
- 引用的C++变量作用域
- c++中的变量作用域
- c/c++中局部变量作用域和生命周期的混淆
- c++中的局部/静态变量作用域
- 多个c++文件和变量作用域