gpt4 book ai didi

c++ - 在 C++ 中执行 try catch 时没有输出

转载 作者:行者123 更新时间:2023-11-30 05:14:43 25 4
gpt4 key购买 nike

我正在 try catch 错误的分配错误。当输入长度为 10000000000000000000000 或其他长度时,就会出现分配错误。不知道为什么没被抓到。任何帮助将不胜感激!

# include <vector>
# include <iostream>


using namespace std;

void length(int m)
{
vector<int> x;

try
{
x.resize(m);
}
catch(std::bad_alloc&)
{
cout << "caught bad alloc exception" << std::endl;
}
}

int main()

{

int l;
cout << "Length" ;
cin >> l ;
length(l);

return 0;
}

更新:

当我对输入值进行硬编码时,它会抛出异常。我不知道为什么会这样。

# include <vector>
# include <iostream>


using namespace std;



void length(int m)
{
vector<int> x;

try
{
x.resize(m);
}
catch(std::bad_alloc&)
{
cout << "caught bad alloc exception" << std::endl;
}
}

int main()

{

int m= 100000000000000000000;
length(m);

return 0;
}

最佳答案

你应该写

if (!(cin >> l)){
// I could not read that into `l`
}

没有异常被捕获的原因可能是

  1. 您的 int 值比您想象的要小(可能是一些 undefined 环绕行为),并且由于分配成功,因此不会抛出异常。

  2. 分配是惰性,因为直到您实际使用内存才分配内存。

  3. 如果 std::bad_alloc 作为匿名临时 抛出,那么它不会在您的捕获站点被捕获。 (除非你的顽皮编译器允许非 const 引用绑定(bind)到匿名临时对象,有些人这样做是作为扩展)。改为编写 catch (const std::bad_alloc&),它在那里被捕获。

关于c++ - 在 C++ 中执行 try catch 时没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com