Possible Duplicate:
What is the proper way to return an object from a C++ function ?
Hi there,
i would like to know whats the difference between the following two functions with respect to the return types?
- MyClass& func1(void)
- MyClass* func2(void)
I always thought this would be the same?
Heinrich
The first one is only capable of returning a reference to a single object and may not be null. Or rather, it should not be null.
The second one may be returning the pointer to a single object, or an array of objects.
In cases where you wish to return a single object that cannot be null, #1 tends to be the preferred form. In cases where a null can be returned #2 has to be used. Some APIs don't return references at all (like QT).
This is strictly a syntactic difference however. These two types are handled exactly the same in the compiled code: a pointer to the object (or array) will be used. That is, strictly speaking, the reference notation & adds no new semantic functionality over a normal pointer.
(This perhaps just summarizes what the other people wrote)
the first one returns reference to an object (or its address). The other one returns pointer, not reference
Major difference: the second one can return NULL
精彩评论