开发者

Which way you prefer to send arguments?

Suppose you have a function:

void fun(int *a, int *b);

Which way you would prefer to send the arguments?

(1.)

int x, y;
fun(&x, &y);

(2.)

int *x, *y;
fun(x, y);

What are the prob开发者_如何学Clems with other way or both are same and their behavior will also be the same?


Usually you use the former if you want the variables on the stack, and the latter if you allocate memory for them on the heap. The stack is typically faster, whereas the heap is typically bigger. So in general, you use the first pattern quite often, and only use the latter when dealing with giant arrays or very large objects.


In C++ we usually pass objects as references. This is a benefit since there is less worry about NULL pointers.

In your second example code, you are passing two uninitialized int * which will cause undefined behavior. You will never be able to assign to *x or *y (technically you can, but it's UB and your program might crash). Prefer the first example code, since you are pointing to actual objects.


I think this is totally irrelevant. The behaviors are the same. Just use what's convenient and common sense. If some pointers are already around, use them. If it's short and no variables store the address, just prefix &, etc. It's not a big deal.


I usually prefer references for output parameters. The second option of yours has the possibilty to pass a null-pointer which the function might want to process in a special way. Also the second is dangerous, because you pass dangling pointers


I tend to agree with Google's c++ style guideline, where they request that input parameters be const references (const &), and output parameters are pointers.

void Foo(const string &in, string *out)

This gives the user an immediate pattern queue that the parameter in (above) is an input parameter, and out is an output parameter.


Either way functionality is same. There is no change in the behavior.

With the second option, if x and y not initialized properly, there is a scope for segmentation fault.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜