c++ - 如何在C++中导致length_error异常

标签 c++

我正在尝试使代码抛出length_error异常。我的目标是检测并处理此异常情况。到目前为止,这是我的尝试:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char * argv[])
{
    string buffer("hi");
    cout<<buffer.max_size()<<endl;
    try {
        while(1) {
            buffer.append(buffer);
        }
    }
    
    catch(length_error &l) {
        cout<<"Caught length_error exception: "<<l.what()<<endl;
    }
    
    catch(exception &e) {
        cout<<"Caught exception: "<<e.what()<<endl;
    }
    return 0;
}
当我运行程序时,我看到字符串的最大大小为18446744073709551599字节。该程序将继续运行,直到所有内存用完为止。然后就安静了。没有异常被抛出。该程序仍在运行,但其CPU使用率从100%降低到0%左右。
附加信息:
作业系统:Mac OS 10.8。
编译器:Clang 5.1
内存:16 GB

最佳答案

我相信您的计算机将进入虚拟内存崩溃,这是因为将字符串增加两个字符很多次的内存消耗。
获得此异常的更有效方法是在一开始创建大小为max_size()+1的字符串。这是修改您的代码以执行此操作的(至少对我而言),它立即引发您期望的异常:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char * argv[])
{
    string buffer("hi");
    cout<<buffer.max_size()<<endl;
    try {
        std::string blah(buffer.max_size()+1, 'X');
    }

    catch(length_error &l) {
        cout<<"Caught length_error exception: "<<l.what()<<endl;
    }

    catch(exception &e) {
        cout<<"Caught exception: "<<e.what()<<endl;
    }
    return 0;
}

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

相关文章:

c++ - 为什么函数中的对象输入不匹配但仍然有效?

c++ - 将 unsigned char* 强制转换为 char* 并将取消引用的指针视为它真的指向 char 是否安全?

c++ - 链接器错误 undefined reference

c++ - SteamVR 覆盖 Controller 输入?

c++ - while() 不同的输出;相同的变量

c++ - 在 C++ 中通过引用传递数组

java - 如何在 Eclipse 中同时解析 Java 和 C++?

android - Termux 不能运行c++程序?

c++ - 错误 C2509 : member function not declared in derived class

c++ - 我可以使用像 bool 这样的数据类型来压缩数据同时提高可读性吗?