Pass by Reference v. Pass by Pointer
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 (ie 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.
Prefer pass by reference. If for nothing else I do it because a reference simply can't be NULL
. It puts an end to so many stupid bugs, debates, contract checks, memory responsibility questions, etc ...
FYI this was asked in a slightly diff way earlier today:
When to pass by reference and when to pass by pointer in C++?
Canonical advice is "pass by ref to const unless av good reason for another choice".
链接地址: http://www.djcxy.com/p/20716.html下一篇: 通过引用传递v。通过指针传递