析构函数导致堆损坏.

Ser*_*nov 1 c++ destructor

我正在使用析构函数,我不明白为什么在main函数终止时我为此代码出错.

#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255): 
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};


int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它输出,但是当我按Enter键时,它会输出"销毁对象",并显示以下错误"这可能是由于堆的损坏,这表示testcpp.exe或其加载的任何DLL中存在错误." .

1
2
3
0 0 0 255
Run Code Online (Sandbox Code Playgroud)

我在Win7上使用VS2010.

eml*_*lai 6

int arr[3]当封闭功能退出时,自动存储持续时间变量将自动解除分配.

尝试delete[]它会导致未定义的行为.只能分配的对象new[]可以取消分配delete[].