const_cast failing in c++ - c++

CallingClass::CallingFunc()
{
SomeClass obj;
obj.Construct(*Singleton::GetInstance()); // passing the listener
// Singleton::GetInstance() returns a static pointer.
//Singleton is derived from IListener
}
SomeClass::Construct(const IListener &listener)
{
IListener* pListener = const_cast<IListener*>(&listener);
}
After const_cast pListener is null.
Is it possible to perform such typecasting?
Thanks

So let me see. You have two-phase initialization, a Singleton, and casting away const, and you're de-referencing an object just to take it's address again? A stray NULL pointer is the least of your concerns, my friend.
Throw it away and write it again from scratch. And pick up a C++ book first.
Just so you know, const_cast cannot produce a null pointer unless it was passed one. GetInstance() must be returning NULL to produce this behaviour, which is formally UB as soon as you de-reference it.

const_cast is basically an instruction to the compiler to ignore the constness of something. Use of it is to be avoided, because you are overriding the compiler protection, and it can lead to a crash as you write something that attempts to update read-only memory.
However, it doesn't actually cause any code to be generated.
Therefore, if this:
IListener* pListener = const_cast<IListener*>(&listener);
results in pListener being NULL, then &listener is NULL, which is impossible (or you are returning a null reference for your singleton, or you are missing something out from your description of the problem).
Having said which I agree strongly with the answer from DeadMG.
Creating an empty object and doing an Init on it (2-phase construction) is to be avoided. Properly created objects should be valid, and if you have an Init method, it isn't.
Removing the constness from anything is to be avoided - it is extremely likely to produce surprising behaviour.
The amount of de-and-rereferencing in that code is going to give anyone a headache.

Two questions:
What are you trying to acheive here?
How much control have you got over the code? (i.e. what are you able to change?)
Without wishing to be unkind I would honestly say that it might be better to start again. There are a couple of issues I would have with this code:
Firstly, the Singleton pattern should ensure that only one of a specific object is ever created, therefore it is usually returned by pointer, reference or some derivative thereof (i.e. boost shared pointer etc.) It need not necessarily be const though and the fact that it is here indicates that the author did not intend it to be used in a non-const way.
Second, you're then passing this object by reference into a function. No need. That's the one of the major features (and drawbacks) of the singleton pattern: You can access it from anywhere. So you could just as easily write:
SomeClass::Construct()
{
IListener* pListener = const_cast<IListener*>(*Singleton::GetInstance());
}
Although this still doesn't really help you. One thing it does do is make your interface a bit clearer. You see, when you write SomeClass::Construct(const IListener&listener) anyone reading your could reasonably imply that listener is treated as const within the function and by using const_cast, you've broken that implied contract. This is a very good reason that you should not use const_cast - at least not in these circumstances.
The fundamental question that you need to ask yourself is when your IListener is const, why do you need to use it in a non-const way within Construct? Either the singleton should not return a const object or your function should not need it to be non-const.
This is a design issue that you need to sort out before you take any further steps.

Related

Return as pointer, reference or object? [duplicate]

I'm moving from Java to C++ and am a bit confused of the language's flexibility. One point is that there are three ways to store objects: A pointer, a reference and a scalar (storing the object itself if I understand it correctly).
I tend to use references where possible, because that is as close to Java as possible. In some cases, e.g. getters for derived attributes, this is not possible:
MyType &MyClass::getSomeAttribute() {
MyType t;
return t;
}
This does not compile, because t exists only within the scope of getSomeAttribute() and if I return a reference to it, it would point nowhere before the client can use it.
Therefore I'm left with two options:
Return a pointer
Return a scalar
Returning a pointer would look like this:
MyType *MyClass::getSomeAttribute() {
MyType *t = new MyType;
return t;
}
This'd work, but the client would have to check this pointer for NULL in order to be really sure, something that's not necessary with references. Another problem is that the caller would have to make sure that t is deallocated, I'd rather not deal with that if I can avoid it.
The alternative would be to return the object itself (scalar):
MyType MyClass::getSomeAttribute() {
MyType t;
return t;
}
That's pretty straightforward and just what I want in this case: It feels like a reference and it can't be null. If the object is out of scope in the client's code, it is deleted. Pretty handy. However, I rarely see anyone doing that, is there a reason for that? Is there some kind of performance problem if I return a scalar instead of a pointer or reference?
What is the most common/elegant approach to handle this problem?
Return by value. The compiler can optimize away the copy, so the end result is what you want. An object is created, and returned to the caller.
I think the reason why you rarely see people do this is because you're looking at the wrong C++ code. ;)
Most people coming from Java feel uncomfortable doing something like this, so they call new all over the place. And then they get memory leaks all over the place, have to check for NULL and all the other problems that can cause. :)
It might also be worth pointing out that C++ references have very little in common with Java references.
A reference in Java is much more similar to a pointer (it can be reseated, or set to NULL).
In fact the only real differences are that a pointer can point to a garbage value as well (if it is uninitialized, or it points to an object that has gone out of scope), and that you can do pointer arithmetics on a pointer into an array.
A C++ references is an alias for an object. A Java reference doesn't behave like that.
Quite simply, avoid using pointers and dynamic allocation by new wherever possible. Use values, references and automatically allocated objects instead. Of course you can't always avoid dynamic allocation, but it should be a last resort, not a first.
Returning by value can introduce performance penalties because this means the object needs to be copied. If it is a large object, like a list, that operation might be very expensive.
But modern compilers are very good about making this not happen. The C++ standards explicitly states that the compiler is allowed to elide copies in certain circumstances. The particular instance that would be relevant in the example code you gave is called the 'return value optimization'.
Personally, I return by (usually const) reference when I'm returning a member variable, and return some sort of smart pointer object of some kind (frequently ::std::auto_ptr) when I need to dynamically allocate something. Otherwise I return by value.
I also very frequently have const reference parameters, and this is very common in C++. This is a way of passing a parameter and saying "the function is not allowed to touch this". Basically a read-only parameter. It should only be used for objects that are more complex than a single integer or pointer though.
I think one big change from Java is that const is important and used very frequently. Learn to understand it and make it your friend.
I also think Neil's answer is correct in stating that avoiding dynamic allocation whenever possible is a good idea. You should not contort your design too much to make that happen, but you should definitely prefer design choices in which it doesn't have to happen.
Returning by value is a common thing practised in C++. However, when you are passing an object, you pass by reference.
Example
main()
{
equity trader;
isTraderAllowed(trader);
....
}
bool isTraderAllowed(const equity& trdobj)
{
... // Perform your function routine here.
}
The above is a simple example of passing an object by reference. In reality, you would have a method called isTraderAllowed for the class equity, but I was showing you a real use of passing by reference.
A point regarding passing by value or reference:
Considering optimizations, assuming a function is inline, if its parameter is declared as "const DataType objectName" that DataType could be anything even primitives, no object copy will be involved; and if its parameter is declared as "const DataType & objectName" or "DataType & objectName" that again DataType could be anything even primitives, no address taking or pointer will be involved. In both previous cases input arguments are used directly in assembly code.
A point regarding references:
A reference is not always a pointer, as instance when you have following code in the body of a function, the reference is not a pointer:
int adad=5;
int & reference=adad;
A point regarding returning by value:
as some people have mentioned, using good compilers with capability of optimizations, returning by value of any type will not cause an extra copy.
A point regarding return by reference:
In case of inline functions and optimizations, returning by reference will not involve address taking or pointer.

When to return a pointer, scalar and reference in C++?

I'm moving from Java to C++ and am a bit confused of the language's flexibility. One point is that there are three ways to store objects: A pointer, a reference and a scalar (storing the object itself if I understand it correctly).
I tend to use references where possible, because that is as close to Java as possible. In some cases, e.g. getters for derived attributes, this is not possible:
MyType &MyClass::getSomeAttribute() {
MyType t;
return t;
}
This does not compile, because t exists only within the scope of getSomeAttribute() and if I return a reference to it, it would point nowhere before the client can use it.
Therefore I'm left with two options:
Return a pointer
Return a scalar
Returning a pointer would look like this:
MyType *MyClass::getSomeAttribute() {
MyType *t = new MyType;
return t;
}
This'd work, but the client would have to check this pointer for NULL in order to be really sure, something that's not necessary with references. Another problem is that the caller would have to make sure that t is deallocated, I'd rather not deal with that if I can avoid it.
The alternative would be to return the object itself (scalar):
MyType MyClass::getSomeAttribute() {
MyType t;
return t;
}
That's pretty straightforward and just what I want in this case: It feels like a reference and it can't be null. If the object is out of scope in the client's code, it is deleted. Pretty handy. However, I rarely see anyone doing that, is there a reason for that? Is there some kind of performance problem if I return a scalar instead of a pointer or reference?
What is the most common/elegant approach to handle this problem?
Return by value. The compiler can optimize away the copy, so the end result is what you want. An object is created, and returned to the caller.
I think the reason why you rarely see people do this is because you're looking at the wrong C++ code. ;)
Most people coming from Java feel uncomfortable doing something like this, so they call new all over the place. And then they get memory leaks all over the place, have to check for NULL and all the other problems that can cause. :)
It might also be worth pointing out that C++ references have very little in common with Java references.
A reference in Java is much more similar to a pointer (it can be reseated, or set to NULL).
In fact the only real differences are that a pointer can point to a garbage value as well (if it is uninitialized, or it points to an object that has gone out of scope), and that you can do pointer arithmetics on a pointer into an array.
A C++ references is an alias for an object. A Java reference doesn't behave like that.
Quite simply, avoid using pointers and dynamic allocation by new wherever possible. Use values, references and automatically allocated objects instead. Of course you can't always avoid dynamic allocation, but it should be a last resort, not a first.
Returning by value can introduce performance penalties because this means the object needs to be copied. If it is a large object, like a list, that operation might be very expensive.
But modern compilers are very good about making this not happen. The C++ standards explicitly states that the compiler is allowed to elide copies in certain circumstances. The particular instance that would be relevant in the example code you gave is called the 'return value optimization'.
Personally, I return by (usually const) reference when I'm returning a member variable, and return some sort of smart pointer object of some kind (frequently ::std::auto_ptr) when I need to dynamically allocate something. Otherwise I return by value.
I also very frequently have const reference parameters, and this is very common in C++. This is a way of passing a parameter and saying "the function is not allowed to touch this". Basically a read-only parameter. It should only be used for objects that are more complex than a single integer or pointer though.
I think one big change from Java is that const is important and used very frequently. Learn to understand it and make it your friend.
I also think Neil's answer is correct in stating that avoiding dynamic allocation whenever possible is a good idea. You should not contort your design too much to make that happen, but you should definitely prefer design choices in which it doesn't have to happen.
Returning by value is a common thing practised in C++. However, when you are passing an object, you pass by reference.
Example
main()
{
equity trader;
isTraderAllowed(trader);
....
}
bool isTraderAllowed(const equity& trdobj)
{
... // Perform your function routine here.
}
The above is a simple example of passing an object by reference. In reality, you would have a method called isTraderAllowed for the class equity, but I was showing you a real use of passing by reference.
A point regarding passing by value or reference:
Considering optimizations, assuming a function is inline, if its parameter is declared as "const DataType objectName" that DataType could be anything even primitives, no object copy will be involved; and if its parameter is declared as "const DataType & objectName" or "DataType & objectName" that again DataType could be anything even primitives, no address taking or pointer will be involved. In both previous cases input arguments are used directly in assembly code.
A point regarding references:
A reference is not always a pointer, as instance when you have following code in the body of a function, the reference is not a pointer:
int adad=5;
int & reference=adad;
A point regarding returning by value:
as some people have mentioned, using good compilers with capability of optimizations, returning by value of any type will not cause an extra copy.
A point regarding return by reference:
In case of inline functions and optimizations, returning by reference will not involve address taking or pointer.

Is there a practical benefit to casting a NULL pointer to an object and calling one of its member functions?

Ok, so I know that technically this is undefined behavior, but nonetheless, I've seen this more than once in production code. And please correct me if I'm wrong, but I've also heard that some people use this "feature" as a somewhat legitimate substitute for a lacking aspect of the current C++ standard, namely, the inability to obtain the address (well, offset really) of a member function. For example, this is out of a popular implementation of a PCRE (Perl-compatible Regular Expression) library:
#ifndef offsetof
#define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field))
#endif
One can debate whether the exploitation of such a language subtlety in a case like this is valid or not, or even necessary, but I've also seen it used like this:
struct Result
{
void stat()
{
if(this)
// do something...
else
// do something else...
}
};
// ...somewhere else in the code...
((Result*)0)->stat();
This works just fine! It avoids a null pointer dereference by testing for the existence of this, and it does not try to access class members in the else block. So long as these guards are in place, it's legitimate code, right? So the question remains: Is there a practical use case, where one would benefit from using such a construct? I'm especially concerned about the second case, since the first case is more of a workaround for a language limitation. Or is it?
PS. Sorry about the C-style casts, unfortunately people still prefer to type less if they can.
The first case is not calling anything. It's taking the address. That's a defined, permitted, operation. It yields the offset in bytes from the start of the object to the specified field. This is a very, very, common practice, since offsets like this are very commonly needed. Not all objects can be created on the stack, after all.
The second case is reasonably silly. The sensible thing would be to declare that method static.
I don't see any benefit of ((Result*)0)->stat(); - it is an ugly hack which will likely break sooner than later. The proper C++ approach would be using a static method Result::stat() .
offsetof() on the other hand is legal, as the offsetof() macro never actually calls a method or accesses a member, but only performs address calculations.
Everybody else has done a good job of reiterating that the behavior is undefined. But lets pretend it wasn't, and that p->member is allowed to behave in a consistent manner under certain circumstances even if p isn't a valid pointer.
Your second construct would still serve almost no purpose. From a design perspective, you've probably done something wrong if a single function can do its job both with and without accessing members, and if it can then splitting the static portion of the code into a separate, static function would be much more reasonable than expecting your users to create a null pointer to operate on.
From a safety perspective, you've only protected against a small portion of the ways an invalid this pointer can be created. There's uninitialized pointers, for starters:
Result* p;
p->stat(); //Oops, 'this' is some random value
There's pointers that have been initialized, but are still invalid:
Result* p = new Result;
delete p;
p->stat(); //'this' points to "safe" memory, but the data doesn't belong to you
And even if you always initialize your pointers, and absolutely never accidentally reuse free'd memory:
struct Struct {
int i;
Result r;
}
int main() {
((Struct*)0)->r.stat(); //'this' is likely sizeof(int), not 0
}
So really, even if it weren't undefined behavior, it is worthless behavior.
Although libraries targeting specific C++ implementations may do this, that doesn't mean it's "legitimate" generally.
This works just fine! It avoids a null
pointer dereference by testing for the
existence of this, and it does not try
to access class members in the else
block. So long as these guards are in
place, it's legitimate code, right?
No, because although it might work fine on some C++ implementations, it is perfectly okay for it to not work on any conforming C++ implementation.
Dereferencing a null-pointer is undefined behavior and anything can happen if you do it. Don't do it if you want a program that works.
Just because it doesn't immediately crash in one specific test case doesn't mean that it won't get you into all kinds of trouble.
Undefined behaviour is undefined behaviour. Do this tricks "work" for your particular compiler? well, possibly. will they work for the next iteration of it. or for another compiler? Possibly not. You pays your money and you takes your choice. I can only say that in nearly 25 years of C++ programming I've never felt the need to do any of these things.
Regarding the statement:
It avoids a null pointer dereference by testing for the existence of this, and it does not try to access class members in the else block. So long as these guards are in place, it's legitimate code, right?
The code is not legitimate. There is no guarantee that the compiler and/or runtime will actually call to the method when the pointer is NULL. The checking in the method is of no help because you can't assume that the method will actually end up being called with a NULL this pointer.

Problem with returning arguments that are const references

I know why the following does not work correclty, so I am not asking why. But I am feeling bad about it is that it seems to me that it is a very big programming hindrance.
#include <iostream>
#include <string>
using namespace std;
string ss("hello");
const string& fun(const string& s) {
return s;
}
int main(){
const string& s = fun("hello");
cout<<s<<endl;
cout<<fun("hello")<<endl;
}
The first cout will not work. the second cout will.
My concern is the following:
Is it not possible to imagine a situation where a method implementor wants to return an argument that is a const reference and is unavoidable?
I think it is perfectly possible.
What would you do in C++ in this situation?
Thanks.
In C++, it is important to establish the lifetimes of objects. One common technique is to decide upon an "owner" for each object. The owner is responsible for ensuring that the object exists as long as it is needed, and deleting it when not needed.
Often, the owner is another object that holds the owned object in an instance variable. The other typical ways to deal with this are to make it a global, a static member of a class, a local variable, or use a reference-counted pointer.
In your example, there is no clear ownership of the string object. It is not owned by the main() function, because it is not a local variable, and there is no other owner.
I feel your pain. I've found other situations where returning a const reference seemed the right thing to do, but had other ugly issues.
Luckily, the subtle gotcha is solved in c++0x. Always return by value. The new move constructors will make things a fast as you could wish.
The technique is valid and is used all the time. However in your first example you are converting a const char* to a temporary std::string and attempting to return it, which is not the same as returning a const-reference to an object stored elsewhere. In the second example you are doing the same thing, but you are using the result before the temporary is destroyed, which in this case is legal but dangerous (see your first case.)
Update: Allow me to clarify my answer some. I'm saying the problem lies in the creation of the temporary and not correctly handling the lifetimes of the objects being created. The technique is a good one, but it (along with many other good techniques) requires the pre- and post-conditions of the functions be met. Part of this burden falls on the function programmer (who should document it) and partly on the client as well.
I think it is a slight weakness of C++. There's an unfortunate combination of two factors:
The function's return is only valid as long as its argument is.
Implicit conversion means that the function's argument is not the object it may appear to be.
I have no sympathy for people who fail to think about the lifetime of objects they have pointers/references to. But the implicit conversion, which certainly is a language feature with subtle pros and cons, is not making the analysis very easy here. Sometimes implicit conversion is bad news, which why the explicit keyword exists. But the problem isn't that conversion to string is bad in general, it's just bad for this function, used in this incorrect way.
The author of the function can in effect disable implicit conversion, by defining an overload:
const char *fun(const char *s) { return s; }
That change alone means the code which previously was bad, works. So I think it's a good idea in this case to do that. Of course it doesn't help if someone defines a type which the author of fun has never heard of, and which has an operator std::string(). Also, fun is not a realistic function, and for more useful routines you might not want to provide an equivalent which operates on char*. In that case, void fun(const char *); at least forces the caller to explicitly cast to string, which might help them use the function correctly.
Alternatively, the caller could note that he's providing a char*, and getting back a reference to a string. That appears to me to be a free lunch, so alarm bells should be ringing where this string came from, and how long it's going to last.
Yes, I agree that there are situations where this is a relevant problem.
I would use a reference-counted pointer to "solve" it.
I think you are asking for trouble in C++98 :)
This can be solved in two ways. First, you could use a shared pointer. In this case, the memory would be managed automatically by the shared_ptr, and you are done! But, this is a bad solution in most cases. Because you are really not sharing the memory between many references. auto_ptr is the true solution for this problem, if you consider using the heap all the time. auto_ptr needs one little crucial improvement that is not there in C++98 to be really usable, that is : Move Semantic!
A better solution is to allow ownership to be moved between references, by using r-value references, which is there in C++0x. So, your piece of code would look like(not sure if the syntax is correct):
string fun(const string& s) {
return s; // return a copy of s
}
....
string s = fun("Hello"); // the actual heap memory is transfered to s.
// the temporary is destroyed, but as we said
// it is empty, because 's' now owns the actual data!
Is it not possible to imagine a situation where a method implementor wants to return an argument that is a const reference and is unavoidable?
Wrong question to ask, really. All you have to do is include whether the returned reference might be to a parameter (passed by reference), and document that as part of the interface. (This is often obvious already, too.) Let the caller decide what to do, including making the temporary into an explicit object and then passing that.
It is common and required to document the lifetimes of returned pointers and references, such as for std::string::data.
What would you do in C++ in this situation?
Often you can pass and return by value instead. This is commonly done with things like std::copy (for the destination iterator in this case).
In the upcoming C++ standard, r-value references can be used to keep your temporary objects 'alive' and would fix the issue that you're having.
You may want to look up perfect forwarding and move constructors as well.

Passing a modifiable parameter to c++ function

Provided, I want to pass a modifiable parameter to a function, what should I choose: to pass it by pointer or to pass it by reference?
bool GetFoo ( Foo& whereToPlaceResult );
bool GetFoo ( Foo* whereToPlaceResult );
I am asking this because I always considered it the best practice to pass parameter by reference (1), but after examining some local code database, I came to a conclusion, that the most common way is (2). Moreover, the man himself (Bjarne Stroustrup) recommends using (2). What are the [dis]advantages of (1) and (2), or is it just a matter of personal taste?
I prefer a reference instead of a pointer when:
It can't be null
It can't be changed (to point to something else)
It mustn't be deleted (by whoever receives the pointer)
Some people say though that the difference between a reference and a const reference is too subtle for many people, and is invisible in the code which calls the method (i.e., if you read the calling code which passes a parameter by reference, you can't see whether it's a const or a non-const reference), and that therefore you should make it a pointer (to make it explicit in the calling code that you're giving away the address of your variable, and that therefore the value of your variable may be altered by the callee).
I personally prefer a reference, for the following reason:
I think that a routine should know what subroutine it's calling
A subroutine shouldn't assume anything about what routine it's being called from.
[1.] implies that making the mutability visible to the caller doesn't matter much, because the caller should already (by other means) understand what the subroutine does (including the fact that it will modify the parameter).
[2.] implies that if it's a pointer then the subroutine should handle the possibility of the parameter's being a null pointer, which may be extra and IMO useless code.
Furthermore, whenever I see a pointer I think, "who's going to delete this, and when?", so whenever/wherever ownership/lifetime/deletion isn't an issue I prefer to use a reference.
For what it's worth I'm in the habit of writing const-correct code: so if I declare that a method has a non-const reference parameter, the fact that it's non-const is significant. If people weren't writing const-correct code then maybe it would be harder to tell whether a parameter will be modified in a subroutine, and the argument for another mechanism (e.g. a pointer instead of a reference) would be a bit stronger.
Advantages to passing by reference:
Forces user to supply a value.
Less error-prone: Handles pointer dereferencing itself. Don't have to check for null inside.
Makes the calling code look much cleaner.
Advantages to passing pointer by value:
Allows null to be passed for "optional" parameters. Kinda an ugly hack, but sometimes useful.
Forces caller to know what is being done w/ the parameter.
Gives the reader half a clue of what might be being done w/ the parameter without having to read the API.
Since reference passing is in the language, any non-pointer parameters might be getting modified too, and you don't know that pointer values are being changed. I've seen APIs where they are treated as constants. So pointer passing doesn't really give readers any info that they can count on. For some people that might be good enough, but for me it isn't.
Really, pointer passing is just an error-prone messy hack leftover from C which had no other way to pass values by reference. C++ has a way, so the hack is no longer needed.
One advantage to passing by reference is that they cannot be null (unlike pointers), obviating the need to null-check every out parameter.
I'd recommend that you consider (may not be best for every situation) returning Foo from the function rather than modifying a parameter. Your function prototype would look like this:
Foo GetFoo() // const (if a member function)
As you appear to be returning a success/failure flag, using an exception might be a better strategy.
Advantages:
You avoid all of the pointer/reference issues
Simplifies life for the caller. Can pass the return value to other functions without using a local variable, for example.
Caller cannot ignore error status if you throw an exception.
Return value optimization means that it may be as efficient as modifying a parameter.
I choose #2 because it obvious at the point of call that the parameter will be changed.
GetFoo(&var) rather than GetFoo(var)
I prefer pass by reference for just const references, where I am trying to avoid a copy constructor call.
Pass by reference, and avoid the whole NULL pointer problem.
I seem to recall that in c++ references where not null and pointers could be. Now I've not done c++ for a long time so my memory could be rusty.
The difference here is relatively minor.
A reference cannot be NULL.
A nullpointer may be passed.
Thus you can check if that happens and react accordingly.
I personally can't think of a real advantage of one of the two possibilities.
I find this a matter of personal taste. I actually prefer to pass by reference because pointers give more freedom but they also tend to cause a lot of problems.
The benefit to a pointer is that you can pass nothing, ie. use it as if the parameter was completely optional and not have a variable the caller passes in.
References otherwise are safer, if you have one its guaranteed to exist and be writeable (unless const of course)
I think its a matter of preference otherwise, but I don't like mixing the two as I think it makes maintainace and readability of your code harder to do (especially as your 2 functions look the same to the caller)
These days I use const references for input parameters and pointers for out parameters. FWIIW, Google C++ Style Guide recommends the same approach (not that I always agree with their style guide - for instance they don't use exceptions, which usually does not make much sense)
My preference is a reference. First, because it rhymes. :) Also because of the issues pointed out by other answers: no need to dereference, and no possibility of a reference being NULL. Another reason, which I have not seen mentioned, is that when you see a pointer you cannot be sure whether or not it points to dynamically allocated memory, and you may be tempted to call delete on it. A reference, on the other hand, dispenses with any ambiguity regarding memory management.
Having said that, there are of course many cases when passing a pointer is preferable, or even necessary. If you know in advance that the parameter is optional, then allowing it to be NULL is very useful. Similarly, you may know in advance that the parameter is always dynamically allocated and have the memory management all worked out.