为什么构造函数没有调用数组中的第二个对象

why constructor is not getting call for second object in an array

考虑这个程序

#include <iostream>

using namespace std;

class sample
{
public:
    sample()
    {
        cout << "consructor called" << endl;
        throw 5;
    }
    void test()
    {
        cout << "Test function" << endl;
    }
};

int main()
{
    sample *s = nullptr;

    try
    {
        s = new sample[5];
        cout << "allocated" << endl;
    }
    catch(bad_alloc& ba)
    {
        cout << ba.what() << endl;
    }
    catch (const int& f)
    {
        cout << "catcting exception";
    }
    return 0;
}

我觉得流程应该是这样的。

1. Allocate the memory for 5 object.
2. call the constructor for each object one by one.

但是在调用构造函数时,我抛出了一个异常,该异常已得到处理。我的疑问是为什么构造函数不再被第二个对象调用??

new simple[5]会为5个simple分配内存,然后开始一个一个构建。由于第一个做了 throw 5,其他 4 个没有构建。

对象的创建是有顺序的,不可能一次创建完五个对象。当创建第一个对象时,您的构造函数将被调用,并且当它抛出异常时,它将控制权移至异常处理程序块。

您的异常处理程序将打印适当的消息并正常退出。

尝试删除 throw 5;