【问题标题】:get more details from bad_alloc?从 bad_alloc 获取更多详细信息?
【发布时间】:2013-08-17 14:47:50
【问题描述】:

因为 vector 得到 long unsigned int 调用 f(-1) 抛出 bad_alloc。我怀疑是用 2147483648 拨打电话,实际上是 18446744073709551615,因为它是 x64 系统。如何获取有关错误详细信息的信息?这可能是笼统的,我怎样才能得到比e.what()更多的细节?

void f(int i){
    vector<int> v(i);
    printf("vector size: %d", v.size());
}

int main(int argc, char** argv) {
    //f(1); // vector size: 1
    try{
    f(-1); // terminate called after throwing an instance of 'std::bad_alloc'
           //what():  std::bad_alloc
    }catch(std::bad_alloc& e){
        printf("tried to allocate: %d bytes in vector constructor", e.?);
    }
    return 0;
}

【问题讨论】:

  • 您希望看到什么样的附加信息?
  • 与您的问题无关,您调用的向量构造函数采用size_t 参数,而您传递的是int。提高警告级别,你的编译器会警告你这些事情。
  • 是的,这是真的,我知道,这只是一个简短的测试,重要的是当通过 -1 时我会得到什么
  • 运算符 new 通常使用 malloc() 实现,malloc 不提供任何额外信息。如果 malloc 由于操作系统调用失败而失败,您可以尝试查看 errno。
  • errno 只有 int 集,没有细节,不是吗?

标签: c++ exception memory vector stl


【解决方案1】:

就标准而言,除了what() 提供的信息(顺便说一下,其内容留给实现)之外,没有其他信息。

你可以做的是向vector 提供你自己的分配器,它会抛出一个派生自bad_alloc 的类,但它也指定了在捕获它时要检索的信息(例如所需的内存量)。

【讨论】:

  • 如果不考虑标准,:p,知道如何在向量构造函数中检索 -1 变成的内容吗?
  • 如果只是想了解-1变成了什么,你可以这样做std::cerr&lt;&lt;std::vector&lt;int&gt;::size_type(-1);
  • 我做了并且得到了:18446744073709551615
  • @restart.localhost.localdomain: 告诉我你在 64 位系统上运行。 -1 在 2 的补码算法中是“所有位开启”,并且在转换为 std::vector&lt;int&gt;::size_type(这是一个无符号类型)时,它被转换为相应的“所有位开启”值(请注意,此转换是实现定义的)。对于 64 位类型,这是 18446744073709551615(即 2^64-1)。
【解决方案2】:
#include <vector>
#include <iostream>

template <typename T>
std::vector<T> make_vector(typename std::vector<T>::size_type size, const T init = T()) {
    try {
        return std::vector<T>(size, init);
    }
    catch (const std::bad_alloc) {
        std::cerr << "Failed to allocate: " << size << std::endl;
        throw;
    }
}

int main()
{
    make_vector<int>(std::size_t(-1));
    return 0;
}

保留而不是初始化可能更适合。 请注意复制省略/返回值优化和移动。

【讨论】:

  • 这不只是 std::cerr 的扩展版本::size_type(-1); ?不过这也回答了我的问题,谢谢
  • 我不明白你的问题。随意替换 cerr 和 throw 行,用你想要的任何东西,可能会抛出 custom_bad_alloc。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多