placement new -- what am I doing wrong?

R

Roy Smith

After 6 or 7 years of doing C++, I've never had a need to use
placement new, but I'm playing with it now just to make sure I
understand the concept. I thought I did, but my compiler (g++ i686-
apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465))
disagrees :) When I compile this:

#include <stdlib.h>

class MyClass {
int i;
};

int main(int, const char**) {
void* block = malloc(sizeof(MyClass));
MyClass* m = new(block) MyClass;
return 0;
}

I get:

new.cpp: In function ‘int main(int, const char**)’:
new.cpp:9: error: no matching function for call to ‘operator new(long
unsigned int, void*&)’
<built-in>:0: note: candidates are: void* operator new(long unsigned
int)

Changing it to "::new" gives essentially the same error. What am I
not groking here?
 
A

Alf P. Steinbach

* Roy Smith:
After 6 or 7 years of doing C++, I've never had a need to use
placement new, but I'm playing with it now just to make sure I
understand the concept. I thought I did, but my compiler (g++ i686-
apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465))
disagrees :) When I compile this:

#include <stdlib.h>

class MyClass {
int i;
};

int main(int, const char**) {
void* block = malloc(sizeof(MyClass));
MyClass* m = new(block) MyClass;
return 0;
}

I get:

new.cpp: In function ‘int main(int, const char**)’:
new.cpp:9: error: no matching function for call to ‘operator new(long
unsigned int, void*&)’
<built-in>:0: note: candidates are: void* operator new(long unsigned
int)

Changing it to "::new" gives essentially the same error. What am I
not groking here?

#include <new>

By the way, using '::new' is absolutely recommended.

Otherwise you risk picking up a placement new definition from the class.


Cheers & hth.,

- Alf
 
Z

ZikO

#include said:
class MyClass {
int i;
};

int main(int, const char**) {
void* block = malloc(sizeof(MyClass));
MyClass* m = new(block) MyClass;
return 0;
}

If you know what you are doing here just ignore me ^^

Is this accident you are using this form of new (im sorry i forgot how
it is called). new has usually this form:

MyClass* pX = new MyClass;

Secondly, are you aware, you have to explicitly call the destructor.
when you use this form of new. Something like this below:

m->MyClass::~MyClass();


Regards
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top