Mail Archives: djgpp/1999/12/23/14:26:32
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 <iostream>
: #include <cstdlib>
: 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 <iostream>
#include <cstdlib>
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 !!!
- Raw text -