Mail Archives: djgpp/1999/12/22/22:18:33
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().
> Valkir (jfd50 AT videotron DOT ca) wrote:
> : Here's the code:
> : int main()
> : [...]
--
Weiqi Gao
weiqigao AT a DOT crl DOT com
- Raw text -