繁体   English   中英

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM