andrei31

placement new vs assignment

Nov 29th, 2018
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. /*
  2.  * Comparing placement new against assignment.
  3.  *
  4.  * In the code below from main, using placement new won't
  5.  * call the destructor of the Point(2,3) that was created in main, so
  6.  * it's just like a std::move let's say to location pointed by pptr.
  7.  *
  8.  * While using the assignment will copy from a const Point& to a
  9.  * new Point and the Point(2,3) created in main will then have its
  10.  * destructor called (since it's a one-off created Point only for that
  11.  * assignment expression), so you'll see an additional "destroying point"
  12.  * output line compared to the first one.
  13.  *
  14.  * See[1] for a great explanation of how placement new works.
  15.  * [1] https://stackoverflow.com/questions/35087204/how-c-placement-new-works
  16.  *
  17.  */
  18.  
  19. #include <cstdlib>
  20. #include <iostream>
  21. #include <new> // Needed for placement 'new'.
  22. #include <string>
  23.  
  24. struct Point
  25. {
  26.     int x_, y_;
  27.  
  28.     Point() { std::cout << "default point constructor\n"; }
  29.     Point(int x, int y): x_(x), y_(y) {
  30.       std::cout << "constructor call of " << *this << '\n';
  31.     }
  32.     ~Point() { std::cout << "destroying point\n"; }
  33.  
  34.     friend std::ostream& operator<<(std::ostream &out, const struct Point &p) {
  35.       out << "Point(" << p.x_ << ", " << p.y_ << ")";
  36.       return out;
  37.     }
  38. };
  39.  
  40. int main() {
  41.   Point* pptr = (Point*)malloc(sizeof(Point));
  42.  
  43.   // how is placement new different here?
  44.   new(pptr) Point(2,3);
  45.  
  46.   // than a simple assignment
  47.   //*pptr = Point(2,3);
  48.  
  49.   // See comment at the top of the file for difference or try it
  50.   // yourself to inspect output.
  51.  
  52.   std::cout << "Done with constructing " << *pptr << ", will deallocate memory now.\n";
  53.   pptr->~Point();
  54.   free(pptr);
  55.  
  56.   return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment