Well, I suppose I'll add my little stone to the edifice... though I am not sure it will even be read.
This is a matter of ownership of the memory, it is the role of your interface to convey this meaning: "Will this method take ownership or not".
To better express ownership, it is usually bad to use raw pointers. The STL has the bastard auto_ptr which is better suited to the task (I am waiting for the upcoming unique_ptr rather impatiently there).
For a method, there are several ways to accept parameters:
// Value
void method(T);
// Reference
void method(T&);
// Pointer
void method(T*);
// Smart Pointer
void method(std::auto_ptr<T>);
I skipped the cv-qualification bit because it's irrelevant there.
The point is that out of these 4 solutions, the intent is clear:
- Value / Reference / Pointer: the caller is responsible for the memory
auto_ptr the method takes ownership of the memory, this means that the caller cannot use the variable afterward
std::auto_ptr myT = std::auto_ptr(new T());
method(myT);
assert(myT.get() == 0); // myT does not hold anything any longer!
Of course, that's why auto_ptr is a wild beast out there, since it does not respect the convention that a copying an object leaves the copied object apparently unchanged: normally all the public methods should give the same result before and after, reference counting being a corner case here if you expose it.
So, your interface should be clearer if whether or not the caller should expect the method to take ownership or not, a simple way is to use overloading.
void method(T*); // do something
void method(std::auto_ptr<T> p)
{
method(p.get());
}
Easy enough, you are now clear on who handles the memory!
With the same reasonment you can also use this overloading trick to automatically check a pointer for nullity.
void method(T&); // do something
void method(T* p)
{
if (p) method(*p); else throw NullPointer("method");
}
But I would avoid abusing the trick, you'll end up with thousands of methods.
So just remember: ownership semantic is best expressed in CODE rather than in comments.
Which you will immediately mix with Use RAII to manage resources which means here that you should never allocate memory to a raw pointer: use a smart pointer to express ownership of the resource, and a raw pointer to point to existing objects you do not own (and that might possibly be null, otherwise a reference is better ;) ).