Okay so let me get this straight.
When you allocate raw memory you should only delete raw data?
So say for example I create 10 raw datas
|
void *ptr = operator new (10);
|
The part I am confused on is how to delete it. The documents sound like this
But that seems to me as if it would only deallocate the first of the 10 or is it actually deallocating all 10 of the raw data?
Also I see so even if you have 5 constructed and 5 raws you would just want to deallocate all of it and not call the destructor on the first 5?
I was thinking you'd have to call the destructor on the ones constructed something like this maybe?
1 2 3 4 5 6
|
void deallocate( T *ptr , const std::size_t n )
{
for( int i = 0; i < n; ++i )
(ptr + i)->~T();
operator delete (static_cast<void *>( ptr ) );
}
|
Here is a full example of where I am confused
10 raw data created
5 of those 10 raw datas are constructed
how do I delete it properly without a memory leak
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
//is this correct?
#include <iostream>
class Test
{
public:
Test(){ std::cout << "Constructed" << std::endl; }
~Test(){ std::cout << "Destructed" << std::endl; }
};
int main()
{
const int SIZE = 10;
void *ptr = operator new (SIZE); //Allocate 10 raw data
for( int i = 0; i < SIZE / 2; ++i )
new (ptr+i) Test; //constructing 5 objects in place of raw data
for( int i = 0; i < SIZE / 2; ++i )
static_cast<Test *>( (ptr + i) )->~Test(); //destructing 5 objects
operator delete (ptr ); //deleteing all 10 raw data
}
|
On a side note I was thinking I have a better idea for my push_front method
Instead of having one storage I'll have two
So say for example capacity is at 10
Then I'll make the capacity of both of them to initalize at 5.
now we have something like this
storage 1: storage 2:
[][][][][] [][][][][]
Now we push back 1 it looks like this
storage 1: storage 2:
[][][][][] [1][][][][]
undefined
We push back 3 more numbers in increasing order
it now looks like
storage 1: storage 2:
[][][][][] [1][2][3][4][]
We now want to push front 3 numbers ( increasing from the last values 5 , 6, 7 )
it looks like this
[5][6][7][][] [1][2][3][4][]
We push back 2 more numbers 8 and 9 it now looks like:
[5][6][7][][] [1][2][3][4][8][9][][][][]
Index 0 in the container is now the largest index in the first storage
so it looks like
[0] == 7
[1] == 6
[2] == 5
[3] == 1
[4] == 2
[5] == 3
[6] == 4
[7] == 8
[8] == 9
Index starts from right to left in the storage 1 then continues from left to right in storage 2.
Does this sound like a more effective way versus copying the old data into a new larger memory block?