H5W3
当前位置:H5W3 > 其他技术问题 > 正文

C++ 为什么类的析构函数在循环中被直接调用?

如下代码中,循环构造Box对象并插入数组;但是为什么每一次循环都调用了析构函数,且如此循环析构后不影响操作数组中对象的成员属性、成员函数

class Box {
public:
    static int count;
    ~Box();
    Box(int, int, int);
    // ...
}
// ...
Box::Box(int lv = 1, int bv = 1, int hv = 1) : l(lv), b(bv), h(hv) {
    cout << "creating new Box(" << ++count << "/" << C_MAX << ")." << endl;
}
Box::~Box() {
    cout << "delete one(" << count-- << "/" << C_MAX << ")." << endl;
}
// ...
void test() {
    int x, t;
    Box *bs = (Box *) calloc(C_MAX, sizeof(Box));
    srand((unsigned) time(NULL));
    for (x = 0; x < C_MAX; x++) {
        t = int(rand() / 1000);
        if (t < 1) {
            bs[x] = Box::Box();
        } else {
            bs[x] = Box::Box(t, t, t);
        }
    }
    // ...
    for (x = 0; x < C_MAX; x++)
        cout << "Box" << (x + 1) << " volume = " << bs[x].volume() << endl;
    // ...
    free(bs);
}

控制台输出如下:
循环析构截图.png

回答:

bs[x] = Box::Box();

  1. Box::Box() 创建了一个新的临时对象 (构造)
  2. 临时对象对拷贝(移动)至 bs[x] (这里没有构造)
  3. 临时对象析构 (析构)

bs 中的对象从来没有被构造过。很多时候使用没有被构造的对象是一个未定义行为。你的程序就是一例。

clss.cdtor/1 :

  1. For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior. For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior.

本文地址:H5W3 » C++ 为什么类的析构函数在循环中被直接调用?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址