【问题标题】:how to cause bad_alloc如何导致bad_alloc
【发布时间】:2015-10-04 16:14:10
【问题描述】:

我必须为我的单元测试导致 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;
};

【问题讨论】:

  • 尝试分配一个非常大的值数组。
  • @AnonMail 问题是,如果没有 bad_alloc,我只需要一个值。
  • 您正在尝试将压力测试作为单元测试进行。通常不推荐这种方式,而且如果不添加一些代码也很难实现,至少使用编译器指令,例如#ifdef TEST_3等。

标签: c++ exception new-operator throw bad-alloc


【解决方案1】:

你可以利用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());
}

【讨论】:

    【解决方案2】:

    您可以在单元测试中明确地 throwstd::bad_alloc。例如

    #include <iostream>
    #include <new>
    
    void test_throw()
    {
        throw std::bad_alloc();
    }
    
    int main()
    {
        try
        {
            test_throw();
        }
        catch (std::bad_alloc& ba)
        {
            std::cout << "caught";
        }
    }
    

    【讨论】:

    • 我不能改变任何函数,我只能在这个函数中传递一个Value参数。
    • 除了throw 之外,导致std::bad_alloc 的唯一方法是在while 循环中一遍又一遍地调用insert,直到内存不足。我不建议这样做,因为您会泄漏所有这些指针,并且在使用所有内存时可能会导致其他事情崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2014-12-21
    • 2019-11-22
    • 1970-01-01
    • 2014-10-20
    • 2012-03-16
    相关资源
    最近更新 更多