Advertisement
kenpusney

ctor_dtor.cpp

Jul 28th, 2022 (edited)
1,108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.54 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct foo {
  5.   foo() {
  6.     cout << "ctor" << endl;
  7.   }
  8.  
  9.   ~foo() {
  10.     cout << "dtor" << endl;
  11.   }
  12. };
  13.  
  14. int main() {
  15.   foo foo_ {};  // "ctor" of foo_; stack allocation
  16.   foo* bar = new foo {}; // "ctor" of bar; heap allocation
  17.   foo* baz = new foo {}; // "ctor" of baz; heap allocation
  18.  
  19.   new (&foo_) foo {}; // "ctor" of foo_; placement new
  20.  
  21.   delete(bar); // "dtor" of bar; heap destruction
  22.   ::operator delete(baz); // nothing; heap deallocation
  23.  
  24.   // "dtor" of foo_; stack destruction
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement