alternate to new operator?

Started by
3 comments, last by Wraith 24 years, 1 month ago
Does anyone know of a way to create a new c++ object in a specific memory location? In my game I am trying to allocate a large block of memory and then create objects within it. Is there any way to do this and have the objects still call their constructors and deconstructors? Thank you, Wraith
[email=cdickinson@scu.edu]Wraith[/email]BasketQase Software
Advertisement
// Globals#define MEMORY_REQUIRED 1024class ExampleClassA{    public:        float SomeData;};class ExampleClassB{    public:        int SomeData;        double SomeOtherData;};void* MemoryPointer;ExampleClassA* ClassA;ExampleClassB* ClassB;void main ( ) // Or WinMain or whatever{    MemoryPointer = (void *)(new char[MEMORY_REQUIRED]);//  This next part''s theoretical; in practice, you''ll//  probably get an error:    ClassA = (ExampleClassA *)MemoryPointer;    ClassB = (ExampleClassB *)(MemoryPointer + (sizeof ExampleClassA));}

I have no idea if that will work. It''s probably possible in Assembly, but I don''t know if the C/C++ compiler will allow it.

~CGameProgrammer( );

~CGameProgrammer( );Developer Image Exchange -- New Features: Upload screenshots of your games (size is unlimited) and upload the game itself (up to 10MB). Free. No registration needed.
Actually, if you want a bunch of objects in a "specific location" why don''t you make an array of them - that will allocate them sequentially from the array head.

It's only funny 'till someone gets hurt.And then it's just hilarious.Unless it's you.
There is a C++ construct made specifically for this - "placement new":

ptr = new ( <location> ) type( <constructor arguments> );

Constructors and destructors will be called, but you'll have to be careful about deallocation. This might be what you're looking for, though. Overloading class-specific new operators may be a better alternative, depending on what you're trying to do.


Edited by - spock on 3/8/00 2:41:04 AM
If you''re only developing for win32, you might want to look into creating a new heap for arrays of objects. Look into HeapCreate() and HeapDestroy(). It allows you to store an array of objects in it''s ''own'' memory area, which I''m guessing is what you want to do.

Hope that helps,
Jon Stelly

This topic is closed to new replies.

Advertisement