Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Comparing placement new against assignment.
- *
- * In the code below from main, using placement new won't
- * call the destructor of the Point(2,3) that was created in main, so
- * it's just like a std::move let's say to location pointed by pptr.
- *
- * While using the assignment will copy from a const Point& to a
- * new Point and the Point(2,3) created in main will then have its
- * destructor called (since it's a one-off created Point only for that
- * assignment expression), so you'll see an additional "destroying point"
- * output line compared to the first one.
- *
- * See[1] for a great explanation of how placement new works.
- * [1] https://stackoverflow.com/questions/35087204/how-c-placement-new-works
- *
- */
- #include <cstdlib>
- #include <iostream>
- #include <new> // Needed for placement 'new'.
- #include <string>
- struct Point
- {
- int x_, y_;
- Point() { std::cout << "default point constructor\n"; }
- Point(int x, int y): x_(x), y_(y) {
- std::cout << "constructor call of " << *this << '\n';
- }
- ~Point() { std::cout << "destroying point\n"; }
- friend std::ostream& operator<<(std::ostream &out, const struct Point &p) {
- out << "Point(" << p.x_ << ", " << p.y_ << ")";
- return out;
- }
- };
- int main() {
- Point* pptr = (Point*)malloc(sizeof(Point));
- // how is placement new different here?
- new(pptr) Point(2,3);
- // than a simple assignment
- //*pptr = Point(2,3);
- // See comment at the top of the file for difference or try it
- // yourself to inspect output.
- std::cout << "Done with constructing " << *pptr << ", will deallocate memory now.\n";
- pptr->~Point();
- free(pptr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment