开发者

Difference between "MyClass& func1(void)" and "MyClass* func2(void)" [duplicate]

This question already has answers here: 开发者_开发问答 Closed 12 years ago.

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?

  1. MyClass& func1(void)
  2. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜