我必须为我的单元测试造成bad_alloc(基本上,对于100%的代码覆盖率,我无法更改某些功能)。我该怎么办?
这是我的代码示例。我必须在这里某处导致bad_alloc。

bool insert(const Value& v) {
    Value * new_value;
    try {
        new_value = new Value;
    }
    catch (std::bad_alloc& ba){
        std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
        return false;
    }
    //...
    //working with new_value
    //...
    return true;
};

最佳答案

您可以利用overloading class-specific operator new 的可能性:

#include <stdexcept>
#include <iostream>

#define TESTING

#ifdef TESTING
struct ThrowingBadAlloc
{
    static void* operator new(std::size_t sz)
    {
        throw std::bad_alloc();
    }
};
#endif

struct Value
#ifdef TESTING
 : ThrowingBadAlloc
#endif
{
};

bool insert(const Value& v) {
    Value * new_value;
    try {
        new_value = new Value;
    }
    catch (std::bad_alloc& ba){
        std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
        return false;
    }
    //...
    //working with new_value
    //...
    return true;
};

int main()
{
    insert(Value());
}

关于c++ - 如何导致bad_alloc,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32935577/

10-10 09:08