if placement new on objects created on stack:
struct s{ s() { std::cout << "c\n";} ~s() { std::cout << "d\n";} }; int main() { s s1[3]; for(int i=0; i< 3; ++i) s* news = new (&s1[i]) s(); }
i get:
c c c c c c d d d
so not getting destructors first 3 objects, safe? if override memory objects allocated on heap/stack , objects not have free resources in destructors still safe?
your output not unexpected - placement new
not invoke destructor of potential object stored in memory location you're accessing. need explictly invoke destructor of object occupies memory location you're trying use in order use placement new
safely.
struct s { s() { std::cout << "c\n"; } ~s() { std::cout << "d\n"; } }; int main() { // 3 's' instances constructed here. s s1[3]; // (!) need explicitly destroy existing // instances here. for(int = 0; < 3; ++i) { s1[i].~s(); } for(int = 0; < 3; ++i) { // 3 's' instances constructed here. s* news = new(&s1[i]) s(); } // 3 's' instances destroyed here. }
output:
c c c d d d c c c d d d
Comments
Post a Comment