new char(10) is wrong, but what was it doing?

I spent a long time puzzling over a crashing program and realised that I'd put

ptr = new char(10);

where I should have had

ptr = new char[10];

But I noticed that the wrong version didn't make the compiler issue a warning. So new char(10) must have a meaning? Is it a construction you'd ever use purposely?



That's placement new - in this case it would be equal to
 
ptr = (char*)10;


so that returns a char* with the value 10. It assumes you already own that memory.

If you'd do that with a class the constructor of that class would also be called.

The only reason I can think of right now why one would use this is if you use a memory pool. Normally that's not the case, so you can probably just ignore the existence of that for now.
That's placement new


Err... no it's not.

It's creating one int with new and initializing it with the value of 10.

Similar to this:

1
2
ptr = new int;
*ptr = 10;


EDIT:

as for why you'd use it, it's more useful with classes than basic types because it allow you to call a specific constructor:

1
2
3
4
5
// some class's constructor:
SomeClass::SomeClass(int a, int b, int c) { }

// calling that ctor with new:
SomeClass* foo = new SomeClass(1,2,3);
Last edited on
Now I've seen your example with a class name, it seems obvious. I can't work out why I couldn't work it out! Thanks.
Last edited on
Stupid me. Yeah sorry disch, I got stuff like that sometimes. I shouldn't make posts after 8pm anymore, I just don't function.
Topic archived. No new replies allowed.