C Programming FAQs: Frequently Asked Questions
#include <memory> using namespace std; #include "Car.hpp" typedef auto_ptr<Car> CarPtr; void f(Car& c) { c.startEngine(); // ... } <-- 1 void g(CarPtr p) { p->startEngine(); // ... } <-- 2 int main() { CarPtr p(new Car()); f(*p); <-- 3 g(p); <-- 4 }
(1) The Car object is not deleted at this line (2) The Car object is deleted at this line (3) Pass-by-reference; *p can be used after this line (4) Pass-by-auto_ptr; *p cannot be used after this line If the intent is for the caller to retain ownership of the object, pass-by-reference should generally be used. If the intent is for the ownership to be passed to the called routine, pass-by-auto_ptr should be used. About the only time pass-by-pointer should be used is when (1) the caller should retain ownership and (2) the called routine needs to handle "nothing was passed" (i.e., the NULL pointer) as a valid input. In the following example, note the explicit test to see if the pointer is NULL. #include <memory> using namespace std; #include "Car.hpp" typedef auto_ptr<Car> CarPtr; void h(Car* p) { if (p == NULL) { // ... } else { p->startEngine(); // ... } } <-- 1 void i() { h(NULL); <-- 2 CarPtr p (new Car()); h(p.get()); <-- 3 // ... } <-- 4
(1) As in pass-by-reference, the Car object is not deleted at this line (2) NULL is a valid parameter to function h() (3) Pass-by-pointer; *p can be used after this line (4) The Car object is deleted at this line |