CppUnit:为什么静态局部变量保持其值

CppUnit: Why does a static local variable keep its value?

本文关键字:局部变量 为什么 静态 CppUnit      更新时间:2023-10-16

我正在尝试使用 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;
}