通过引用通过指针传递 - 优点? [英] Pass by Reference v. Pass by Pointer -- Merits?

查看:169
本文介绍了通过引用通过指针传递 - 优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

传递的指针是首选的C ++传递参考?

是否有指针传递超过传递的好处在C ++中引用?

如何将对象传递给C ++中的函数?


大家好,
我正在努力开发一个面向对象的大型c ++应用程序框架,作为我的化学工程研究生研究的一部分。

我发现我的许多函数都指向自定义对象或STL对象。我发现在编写代码方面,这使得访问存储在其中的函数或变量变得更加困难。



除了简单性之外,是否有任何优点/缺点通过引用v。传递指针?

如果相对于另一个有优势,我可能会重构我的代码以统一使用任何最佳方法。如果没有,我仍然可以重构一致地使用通过引用的可读性(即不必解除引用)。

再次,我想作为我的框架做出最好的决定已经有40多个文件很大,所以我希望尽可能早地实现统一的结构,尽可能使用最佳方法。



谢谢提前!

解决方案

主要区别在于引用不能为NULL(至少不是没有一些恶意编程)。对于语法糖,当需要参数时,我会通过参考。如果我有一个参数是可选的情况,我会传递指针。



总是有例外。如果它符合当前风格,或者由于我与它有关的事情,将它作为指针可能会更方便。


Possible Duplicates:
When pass-by-pointer is preferred to pass-by-reference in C++?
Are there benefits of passing by pointer over passing by reference in C++?
How to pass objects to functions in C++?

Hi all, I'm working to develop a large object oriented c++ application framework as part of my chemical engineering graduate research.

I find that many of my functions take pointers to custom objects or STL objects. I find that in terms of writing code, this makes it harder to access functions or variables stored within.

Aside from simplicity, though, is there any advantages/disadvantages to passing by reference v. passing by pointer?

If there is an advantage to one over the other, I'll probably look to refactor my code to uniformly use whatever approach is optimal. If there isn't I may still refactor to consistently use pass by reference for readability (i.e. not having to dereference)

Again I want to make the best decision as my framework is already 40+ files large, so I want to implement as uniform structure as I can, as early as I can, and with whatever the optimal method is.

Thanks in advance!

解决方案

The main difference is that a reference cannot be NULL (at least not without some malicious programming). For syntactical sugar and when an argument is required, I'd pass by reference. If I had a situation where the argument were optional, I'd pass by pointer.

There are always exceptions. If it conforms to the current style, or due to things I have to do with it, it may be more convenient to have it as a pointer.

这篇关于通过引用通过指针传递 - 优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆