Placement syntax: Difference between revisions

Content deleted Content added
Capitalization
Line 82:
c. you want to separate memory allocation from construction e.g. in implementing a std::vector<> (see std::vector<>::reserve)
 
theThe basic problem is that the constructor is a peculiar function; when it starts off, there is no object, only raw memory. andAnd by the time it finishes, you have a fully initialized object. thereforeTherefore i.) theThe constructor cannot be called on an object ii.) howeverHowever, it needs to access (and initialize) non-static members. thisThis makes calling the constructor directly an error. theThe solution is the placement form of operator new.
 
thisThis operator is implemented as:<source lang="cpp" enclose=div>
 
inline void* operator new( size_t sz, void* here )
Line 93:
 
 
inIn your case, using this is not required as an int is [[Plain old data structure|POD]], it has a trivial constructor. ifIf you want to use it, you could use it this way:<source lang="cpp" enclose=div>
 
for( int i = 0; i < MAX_PIXELS; i++ )
Line 103:
 
</source>
note: doDo not call delete for objects allocated using placement new. ifIf they have non-trivial destructors, call the destructor directly (destruction is an operation on an object and therefore can be called!). and releaseRelease the memory you allocated yourself.
 
=== Preventing exceptions ===