From: alainm AT news DOT RISQ DOT QC DOT CA (Alain Magloire) Subject: Re: djgpp strangeness Newsgroups: comp.os.msdos.djgpp References: <14684.897$Qz2 DOT 16629 AT wagner DOT videotron DOT net> <38618321 DOT 667C7F69 AT a DOT crl DOT com> X-Newsreader: TIN [version 1.2 PL2] Lines: 89 Message-ID: Date: Thu, 23 Dec 1999 16:42:54 GMT NNTP-Posting-Host: 132.206.63.174 X-Complaints-To: abuse AT mcgill DOT ca X-Trace: carnaval.risq.qc.ca 945967374 132.206.63.174 (Thu, 23 Dec 1999 11:42:54 EST) NNTP-Posting-Date: Thu, 23 Dec 1999 11:42:54 EST To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Weiqi Gao (weiqigao AT a DOT crl DOT com) wrote: : Alain Magloire wrote: : > : > If you are writting in C++, then do. If you want to use C, then use C. : > malloc/free are not the preferred way to allocate objects and manage memory, : > in C++. : > : > I do not remember what the std say, but malloc() will give : > uninitialized memory, and free () is not even require to invoke the : > destructor, when the object is collected. : > : > Use new and delete. : I was thinking along the same lines when I tested my theory out with the : following program: : ==========8<==========8<==========8<========== : #include : #include : class X { : int i; : public: : X(int i_) : i(i_) {} : void foo() { cout << "i = " << i << endl; } : void setI(int i_) { i = i_; } : }; : int main() { : X *xp = (X *) malloc(sizeof(X)); : xp->setI(100); : xp->foo(); : } : ==========8<==========8<==========8<========== : And it worked! It's bad style, I know, but does not generate any : errors, and prints out '100' as expected. : Valkir's classes might be more complicated than the one above, which : could cause an error when used with malloc(). No, that is not my point, the point is malloc()/free() will not call the constructor or destructor of a class, reread the post. Try this maybe it will be clearer. As you will see the destructor is not call. If not try comp.lang.c++, they will go more in details. here, '%' is my prompt. % uname -rs SunOS 5.6 % cat mine.cc #include #include class X { public: X() { cout << "counstructor call" << endl; } ~X() { cout << "destructor call" << endl; } void foo() { cout << "method" << endl; } }; int main() { cout << "----------------using malloc/free----------------" << endl; X *xp = (X *)malloc (sizeof(X)); xp->foo(); free (xp); cout << "----------------using new/delete----------------" << endl; X *xx = new X(); xx->foo(); delete xx; return 0; } % g++ -o mine mine.cc % ./mine ----------------using malloc/free---------------- method ----------------using new/delete---------------- counstructor call method destructor call -- au revoir, alain ---- Aussi haut que l'on soit assis, on est toujours assis que sur son cul !!!