Hi Guys,
I was just reading up Lippman to learn more C++ and came across the third syntax of new operator called "placement new".
I have a specific problem where I thot I'll use it, but it turns out to be a total fiasco. :).
My requirement is: I need to create lots and lots of pixel objects (e.g. about 100 matrixs of 800x800 pixels each). So I thot I'll use placement new to pre-allocated memory (line 16) and use it so it'll save time.
But placement new is just returning the address of buffer every time I call it.
Is there something wrong in way I'm using it? or is it that placement new can't be used for my problem and I have to write my own new/delete?
class pixel
{
public:
pixel( ) : _i(0)
{}
void print() { cout << _i << endl ; }
int _i ;
};
//main program to call the array for 4 ints and return average
int main()
{
static const int MAX_PIXELS = 10 ;
int* buffer = new int[MAX_PIXELS] ;
vector<int*> v ;
for( int i = 0; i < MAX_PIXELS; i++ )
{
int* p = new (buffer) int() ;
*p = i ;
v.push_back( p ) ;
cout << "p = " << p << ", *p = " << *p << endl ;
}
cout << endl << "-------printing-------" << endl << endl ;
for( i = 0; i < v.size(); i++ )
{
cout << "v[i] = " << v[i] << ", *v[i] = " << *v[i] << endl ;
}
return 0 ;
}
Output:
p = 002F07A8, *p = 0
p = 002F07A8, *p = 1
p = 002F07A8, *p = 2
p = 002F07A8, *p = 3
p = 002F07A8, *p = 4
p = 002F07A8, *p = 5
p = 002F07A8, *p = 6
p = 002F07A8, *p = 7
p = 002F07A8, *p = 8
p = 002F07A8, *p = 9
-------printing-------
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
v = 002F07A8, *v = 9
Press any key to continue