Placement syntax: Difference between revisions

Content deleted Content added
Line 75:
:<source lang="cpp" enclose=div>
p->~T() ;
 
placement new is used when you do not want operator new to allocate memory (you have pre-allocated it and you want to place the object there), but you do want the object to be constructed. examples of typical situations where this may be required are
a. you want to create objects in memory shared between two different processes
b. you want objects to be created in non-pageable memory
c. you want to seperate memory allocation from construction eg. in implementing a std::vector<> (see std::vector<>::reserve)
 
the basic problem is that the constructor is a peculiar function; when it starts off, there is no object, only raw memory. and by the time it finishes, you have a fully initialized object. therefore i. the constructor cannot be called on an object ii. however, it needs to access (and initialize) non-static members. this makes calling the constructor directly an error. the solution is the placement form of operator new.
 
this operator is implemented as
 
inline void* operator new( size_t sz, void* here )
{ return here ; }
inline void* operator new[]( size_t sz, void* here )
{ return here ; }
 
 
 
in your case, using this is not required as an int is pod, it has a trivial constructor. if you want to use it, you could use it this way:
 
for( int i = 0; i < MAX_PIXELS; i++ )
{
int* p = new (buffer+i) int(i) ; // specify where you want the object
v.push_back( p ) ;
cout << "p = " << p << ", *p = " << *p << endl ;
}
 
 
note: do not call delete for objects allocated using placement new. if they have non-trivial destructors, call the destructor directly (destruction is an operation on an object and therefore can be called!). and release the memory you allocated yourself.
 
</source>