• Advertisement

Archived

This topic is now archived and is closed to further replies.

alternate to new operator?

This topic is 6558 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement

// Globals
#define MEMORY_REQUIRED 1024

class 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( );

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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

Share this post


Link to post
Share on other sites

  • Advertisement