Placement New... Again

closed account (zb0S216C)
There's a few points I'm not quite clear on, and I can't seem to locate answers for them. So, here are my questions:

1) Does the standard guarantee that objects placed within a pre-allocated buffer are stored contiguously? For example:

1
2
3
4
5
6
7
8
9
int main( )
{
    char *Buffer( new char[( 2 * sizeof( int ) )] );
    
    int *Data_A( new( Buffer ) int( 0 ) ), 
        *Data_B( new( Buffer ) int( 1 ) );

    // Deletion...
}

Will it be a guarantee that Data_A & Data_B are stored contiguously?

2) This one is more type-casting-orientated. Here's a cast (using the code above):

 
int *An_Int( reinterpret_cast< int * >( Buffer ) );

If I understand this correctly, An_Int now points to Buffer. When An_Int is dereferenced, the compiler will think An_Int is pointing to an array of ints?

Thanks in advance.

Wazzak
I think that you are stepping them.
You should look into allocators.

2_ An_int is a pointer to int. It can't be anything else.
placement new constructs a new object in the memory space you tell it to. Your question doesn't make sense to me.

Successive calls to placement new with the same memory address will result in new objects being constructed in the same place the previous ones were. You control where the object is constructed. That's the whole point of it.


closed account (zb0S216C)
ne555 wrote:
You should look into allocators.

I prefer to implement my own so I can learn from it.

ne555 wrote:
An_int is a pointer to int. It can't be anything else.

How else would I access the data within the buffer?

cire wrote:
Your question doesn't make sense to me.

Apologies. I didn't know how to word it.

cire wrote:
Successive calls to placement new with the same memory address will result in new objects being constructed in the same place the previous ones were.

Ah. That, I didn't know.

cire wrote:
You control where the object is constructed. That's the whole point of it.

OK, so a second call to new would be:

int *Data_B( new( Buffer + sizeof( int ) ) int( 1 ) ); ?

Damn placement new.

Wazzak
It may be a good exercise. (but don't just ignore at the enemy)

How else would I access the data within the buffer?
Exactly like that. The memory has not stored the type information.
So send your pointer wherever you want, it will only see ints.

Sorry if I worded badly.
closed account (zb0S216C)
ne555 wrote:
Sorry if I worded badly.

No worries :)

Thanks for your help, ne555 & cire, much appreciated :)

Wazzak
Topic archived. No new replies allowed.