unique-pointers-1/p2.cc - Passing unique_ptr as parameter to a function. | Lecture 4 - slide 16 : 40 Program 4 |
// Illustrates how a unique pointer can be passed to a function. // In f1 by value, and in f2 by const reference. // Inspired from Stroustrup 4ed, page 989. #include <iostream> #include <string> #include <memory> #include "point.h" class SomeProblem{}; // Receives a (unique) pointer p by value, works on the pointed object, and returns it. std::unique_ptr<Point> f1(std::unique_ptr<Point> p){ p->displace(1,1); return p; } // Receives a (unique) pointer p by const reference, and works on it. (No need for return). void f2(const std::unique_ptr<Point>& p){ p->displace(1,1); } int main(){ std::unique_ptr<Point> p0{new Point{1,2}}, p1, p2; p1 = move(p0); // The pointer to Point{1,2} is moved from p0 to p1. Must use move! p2 = f1(move(p1)); // ... and moved into f1, where the Point is operated on, // and the pointer is moved out again via return. std::cout << *p2 << std::endl; // (2,3) // The exanple same with f2 that uses a const reference: std::unique_ptr<Point> q0{new Point{1,2}}, q1; q1 = move(q0); // The pointer to Point{1,2} is moved from q0 to q1 f2(q1); // f2 works directly on q1 via a const reference. std::cout << *q1 << std::endl; // (2,3) // point deleted (2,3) // point deleted (2,3) }