What do I do in line 3?
You consult the documentation of a_function
. The usual rule is that functions do nothing about ownership or lifetime unless they say they do. The need for such documentation is pretty clearly established by reference to C APIs, where smart pointers aren't available.
So, if it doesn't say that it deletes its parameter, then it doesn't. If it doesn't say that it keeps a copy of its parameter beyond the time when it returns, until some other specified time, then it doesn't.
If it says something you act accordingly, and if it says nothing then you delete b
(or preferably you write B b; a_function(&b);
instead -- observe that by not destroying the object, the function doesn't need to care how you create the object, you're free to decide).
Hopefully it says whatever it says explicitly, but if you're unlucky it says it via some convention that certain kinds of function in an API take ownership of the objects referred to by their parameters. For example if it's called set_global_B_instance
then you might have a sneaking suspicion that it's going to keep that pointer around, and deleting it immediately after setting it would be unwise.
If it doesn't say anything either way, but your code ends up buggy and you eventually discover that a_function
called delete
on its argument, then you find whoever documented a_function
and you punch them in the nose submit a bug on their documentation.
Frequently that person turns out to be yourself, in which case try to learn the lesson -- document object ownership.
As well as helping to avoid coding errors, smart pointers provide some degree of self-documentation for functions that accept or returns pointers where there are ownership concerns. In the absence of self-documentation, you have actual documentation. For example if a function returns auto_ptr
instead of a raw pointer, that tells you delete
needs to be called on the pointer. You can let the auto_ptr
do that for you, or you can assign it to some other smart pointer, or you can release()
the pointer and manage it yourself. The function you called doesn't care, and doesn't need to document anything much. If a function returns a raw pointer then it has to tell you something about the lifetime of the object referred to by the pointer, because there's no way for you to guess.