CppUnit:为什么静态局部变量保持其值
CppUnit: Why does a static local variable keep its value?
我正在尝试使用 CppUnit 来测试一个方法,该方法应该只在第一次调用时执行一些代码。
class CElementParseInputTests: public CppUnit::TestFixture {
private:
CElement* element;
public:
void setUp() {
element = new CElement();
}
void tearDown() {
delete element;
}
void test1() {
unsigned int parsePosition = 0;
CPPUNIT_ASSERT_EQUAL(false, element->parseInput("fäil", parsePosition));
}
void test2() {
unsigned int parsePosition = 0;
CPPUNIT_ASSERT_EQUAL(false, element->parseInput("pass", parsePosition));
}
我想测试的递归方法:
bool CElement::parseInput(const std::string& input, unsigned int& parsePosition) {
static bool checkedForNonASCII = false;
if(!checkedForNonASCII) {
std::cout << "this should be printed once for every test case" << std::endl;
[...]
checkedForNonASCII = true;
}
[...]
parseInput(input, parsePosition+1)
[...]
}
由于为每个测试用例重新创建然后销毁对象,因此我希望字符串"这应该为每个测试用例打印一次"在运行测试时打印两次,但它只打印一次。我错过了什么?
这就是静态局部变量应该做的事情。
使用说明符 static 在块范围内声明的变量具有静态存储持续时间,但在控件第一次通过其声明时进行初始化(除非它们的初始化是零或常量初始化,可以在首次输入块之前执行(。在所有进一步的调用中,将跳过声明。
这意味着checkedForNonASCII
将初始化为仅在第一次调用中false
一次。对于进一步的调用,将跳过初始化;即 checkedForNonASCII
不会再次初始化为false
。
另一个答案说了什么。 但这可能是你真正想要的:
bool CElement::parseInput(const std::string& input, unsigned int& parsePosition)
{
[...] // your code for validating ascii only characters goes here
if (hasNonAsciiCharacters) {
return false;
}
return parseInputInteral(input, parsePosition);
}
bool CElement::parseInputInternal(const std::string& input, unsigned int& parsePosition)
{
[...]
parseInputInternal(input, parsePosition+1);
[...]
return result;
}
相关文章:
- 为什么编译器并不总是优化局部变量?
- 将局部变量保存到全局向量中,为什么离开局部范围后可以得到这些局部变量?
- 为什么 lambda 对象中的局部变量是常量变量?
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 为什么默认情况下初始化局部变量
- 为什么不能在模板函数中向局部变量添加低级 const 类型
- 为什么静态局部变量的 MSVC 线程安全初始化使用 TLS
- 为什么C++编译器不优化对结构数据成员的读取和写入,而不是不同的局部变量?
- CppUnit:为什么静态局部变量保持其值
- 为什么 C++ 编译器不警告返回对局部变量的引用
- 为什么 C++11 允许您将局部变量声明为 thread_local
- 为什么堆栈中的函数局部变量之间存在内存空间
- 为什么我得到未引用的局部变量
- 在 gdb 中,我按 tab 后,它可以完成我的命令以及局部变量,但为什么 lldb 不能
- 为什么在这段代码中返回对局部变量的引用
- 为什么局部变量不隐藏数组定义中的全局变量
- 为什么由指针和对象构建的局部变量显示不同的输出
- 为什么局部变量在 ubuntu Linux 中 c++ 的 g++ 编译器中初始化为 0
- 为什么VS编译器不会在C++上自动初始化局部变量?
- 为什么从方法返回时局部变量中的数据会损坏