[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.