Default functions implemented by compiler

F

Frederick Gotham

Sekhar posted:

Thanks for making concepts more clear. This code snippet gives me
more thoughts on new operator. Can you just breif on how new operator
works on the above statement.


(I'm going to use "malloc" in this example just to try to make it easier
to understand.)


Here is a normal use of "new":


Type *p = new Type;


This does two things:

(1) It allocates memory.
(2) It constructs an object at that location in memory.


Here is a special use of "new" called "placement new":


Type *p = malloc( sizeof(Type) ); /* This only allocates memory */


::new(p) Type; /* This constructs an object at the address
specified by "p" */



For info on "placement new", try this:

http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10
 
J

Jerry Coffin

[ ... ]
Type *p = malloc( sizeof(Type) ); /* This only allocates memory */

While perhaps reasonable for demo code, for anybody being really
pedantic, this doesn't allocate memory either -- it just causes a
compiler error. Of course, malloc returns a 'void *' and unlike in C,
you can't assign that to a 'Type *' without a cast:

Type *p = static_cast<Type *>malloc(sizeof(Type));
 
F

Frederick

Jerry Coffin posted:
Of course, malloc returns a 'void *' and unlike in C,
you can't assign that to a 'Type *' without a cast:

Type *p = static_cast<Type *>malloc(sizeof(Type));


Of course, you're correct.

99% of the time when I'm using "malloc", I'm writing C code... and so force
of habit made me neglect to cast.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top