explicit constructor call on casted void *

T

Timo Qvist

Hi, I know there is a proper way to do this but I find myself with a
void pointer returned from a malloc( sizeof( class T ) ) which gives me
a pointer to a memory area of the size of class T. The thing is, I need to
use
this data as a class object, but the constructor hasnt been called which
means I get
a zeroed out vptr table; so I tried this...

void foo(int a) {
T *newTptr = (T *)allocptr(); // returns a void * so casted...
newTptr->T::T( a );
}

The second line explicitly calling the constructor actually works with MS
Visual C++ 7,
but not gcc 3.3.3 .... basically get a parse error.. I was kinda surprised
it worked
and am wondering whether someone can help me get it to work on gcc?

Thanks!
/tq
 
V

Victor Bazarov

Timo said:
Hi, I know there is a proper way to do this but I find myself with a
void pointer returned from a malloc( sizeof( class T ) ) which gives me
a pointer to a memory area of the size of class T. The thing is, I need to
use
this data as a class object, but the constructor hasnt been called which
means I get
a zeroed out vptr table; so I tried this...

void foo(int a) {
T *newTptr = (T *)allocptr(); // returns a void * so casted...
newTptr->T::T( a );
}

The second line explicitly calling the constructor actually works with MS
Visual C++ 7,
but not gcc 3.3.3 .... basically get a parse error.. I was kinda surprised
it worked
and am wondering whether someone can help me get it to work on gcc?

Use "placement new":

void foo(int a) {
T *newTptr = new (allocptr()) T(a);
}

V
 
J

Jonathan Mcdougall

Timo said:
void foo(int a) {
T *newTptr = (T *)allocptr(); // returns a void * so casted...
newTptr->T::T( a );

That's illegal: you cannot call constructors. Use placement new :

void *address = allocptr();
T *p = new (address) T(a);


Jonathan
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top