Both are awful in modern C++. |
I thought I'd elaborate on Salem C's point. The problems are (1) passing a raw pointer as a parameter is prone to bugs and (2) returning a raw pointer is prone to even more bugs.
When you pass a pointer as a parameter, there's always the possibility that someone will pass NULL, which will probably crash the program. You can avoid the bug by making the parameter a reference or const reference instead. It's much harder to create a "null reference" and if the caller does, then it's their fault, not yours.
The bigger problem is returning a raw pointer from a function. The calling code needs to know if the function can return NULL. More importantly, the caller needs to know how long the pointer is valid. The answer might be:
- Until the next call to the function, such as when returning a pointer to a static
- Until the caller deletes it, such as when returning an object that was newly created on the heap
- Until the same thread calls the function again.
- Probably others.
Usually, programmers fail to document the answer and the caller is left guessing, which leads to bugs.
You can avoid the problem completely by returning an instance of the object itself. That way the caller can store the result wherever they want for however long they want.
Salem C combined both points when he suggested this:
MyTime computeTimeDifference(const MyTime &t1, const MyTime t2)
This avoids both problems. The parameters are const references so it's very hard to pass in a null object, and the return value is an instance of the class, so you don't have to worry about how long it's valid.