Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. /*
  2.  * Allocate on the stack -- the object is automatically destroyed
  3.  * when the function is exited. This is the preferred way of
  4.  * allocating.
  5.  */
  6. void f() {
  7.     Point p1(1, 2);
  8.     cout << p1.getX() << ", " << p1.getY() << endl;
  9.     p1.move(5, 6);
  10.     cout << p1.getX() << ", " << p1.getY() << endl;
  11. }
  12.  
  13. /*
  14.  * Allocate on the heap, using a safe pointer to keep track of the
  15.  * object. The object is destroyed when the safe pointer goes out
  16.  * of scope (when the function exits).
  17.  */
  18. void g() {
  19.     std::unique_ptr<Point> p(new Point(1, 2));
  20.     cout << p->getX() << ", " << p->getY() << endl;
  21.     p->move(5, 6);
  22.     cout << p->getX() << ", " << p->getY() << endl;
  23. }
  24.  
  25. /*
  26.  * Allocate on the heap, using a raw pointer to keep track of the
  27.  * object. The object must be deleted before the function exits,
  28.  * otherwise there's a memory leak. This kind of allocation should
  29.  * normally not be used in application programs.
  30.  */
  31. void h() {
  32.     Point* p = new Point(1, 2);
  33.     cout << p->getX() << ", " << p->getY() << endl;
  34.     p->move(5, 6);
  35.     cout << p->getX() << ", " << p->getY() << endl;
  36.     delete p;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement