我無法找到我編寫的下面的代碼中的錯誤[雖然沒有任何用途]。 只有在派生類時纔給出SEG FAULT的代碼!
#include < iostream >
#include < cstdlib >
using namespace std;
class Base{
public:
Base(){cout << "Base class constructor" << endl;}
void funv() {};
~Base(){cout << "Base class destructor" << endl;} ;
};
class Derived:public Base{
public:
char *ch;
Derived():ch(new char[6]()){}
~Derived(){
cout << "before" << endl;
delete [] ch;
ch = NULL;
cout << "after" << endl;
}
};
int main(){
Derived * ptr = new Derived;
//memcpy(ptr -> ch,"ar\0",4); // Works when class Derived is derved from base and also when not derived from base
ptr -> ch = const_cast < char* >("ar0"); // Works only when class Derived is not derived from class Base
cout << ptr -> ch[1] << endl;
ptr -> funv();
delete ptr;
return 0;
}
我評論的代碼行嫌上。
我使用的Sun Studio 12
-1:不知道爲什麼你認爲這將是安全的。 – 2014-07-07 17:21:03
@LightnessRacesinOrbit:是的,在問了這個問題超過3年後,即使我現在不知道爲什麼我認爲它會安全:)。感謝您使它注意到 – Arunmu 2014-07-07 18:49:50