I have a newbie question about c++ and destructors. My c++ program gives a segmentation fault after I delete a class pointer if I have declared a destoructor, otherwise I don't and I do not understand why. Help is much appreciated.
main file, where the class is used.
#include <iostream>
#include "foo.h"
int main(int iargc, char *iargv[]){
std::cout<<"helloworld"<<std::endl;
foo *test;
test = new foo[2];
delete test;
}
header file:
#ifndef FOO_H
class foo{
public:
foo();
~foo();
};
#define FOO_H
#endif
foo.cpp
#include "foo.h"
foo::foo(){
};
foo::~foo(){
};
without a delete statement, no problems whatsoever, if I remove the destructor from the header file and the source code, I can delete the class pointer test, but I cannot delete it, while I declared the destructor like this without a segfault.
答案 0 :(得分:5)
You should delete[] test
, in the array form.