开发者

Choosing between reference (T&) and const pointer (T* const)

Is there any reasonable use case, where one should use const pointer over reference?

T obj;
T &r = obj;  // style-1
T* const p = &obj; // style-2

Both the style can be used for the same purpose. I always prefer the 1st style in the code and consider the later style as deprecated. However I still wonder if missed any use 开发者_如何转开发case where 2nd style is better ?

Edit: Not limiting to the above example, I talk in a broader sense,

void foo (T& r); // style-1
void foo (T* const p); // style-2

[I see from few of the answers that, style-2 allows to pass null.]


A const pointer (T* const) can be NULL, and that can be useful when passing arguments to a function or when returning values from a function. For example, if you have a search function, you might want it to return NULL if it didn't find anything. You can't do that if it returns a reference type.


Let me go out on a limb here. Since you explicitly say "const pointer", I'm assuming that you are not talking about function arguments or even function return values. For a function argument passed by copy, the constness is an irrelevant implementation detail:

void foo(T *);          // declaration

void foo(T * const pt)  // implementation,
{ /* ... */ }           // pt is const inside the body (who cares?)

Therefore, the only use case that comes to mind is if you need to make an alias somewhere inside your own code. In that case I'd always prefer the reference. Compare:

for (auto it = box.begin(); it != box.end(); ++it)
{
  T & trinket = *it;     // nice
  T * const ptr = &*it;  // wtpf?

  // ...
}

Since you edited your question: There is obviously a difference for function arguments.

void foo(T &);
void bar(T *);

In foo you are guaranteed to have a workable, mutable object reference; in bar you have to check whether the pointer is not null (giving you the notion of an optional argument). In that sense, T& and T* aren't really comparable.


For function arguments, I much prefer pointers to references, because I can tell at the call site that the parameter is an out parameter. If the function argument is a const reference, then I prefer references.

The other big difference is r can't be null, so if you need it to be, then you need style-2


1) When using reference, the object must be stored in variable. For example, you can't do this:

void funct (T &);
funct (T ("Calling constructor"));

Must do:

void funct (T &);
T obj ("Calling constructor");
funct (obj);

2) When using reference, you cannot test it's value (eg. check if it's NULL which is commonly used)

By everything else, it's the same thing.

I generally use them only if it's important that function is called with true variable as argument. I might be old fashioned, but pointer way is better for me in every other cases.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜