开发者

Good coding: Pointers rather than references? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

As I've been coding C/C++ for about a year now, I've tried to learn the preferred ways for writing good OO and C++ code. That means, when coding, I always look for the best ways when implementing some开发者_JAVA百科thing, rather than just typing something and checking if it works. I've told that in C++ you should use references instead of raw pointers when passing arguments to functions, to make it more safe. So that would be considered as better coding. Although, in many high quality opensource projects(which are C++) they use pointers instead of references. All arguments, returns and stuff are pointers rather than safer references. Even Microsoft's directx uses pointers more than the safer option. I cannot see any benefits by using pointers instead of references, actually I think raw pointers are worse than references(in situations where dynamic alloc isn't needed of course).

So onto my question: why most of the opensource projects use pointers, when there are better ways available?


Not sure if that's an indication of quality or not, but according to Google's C++ Style Guide,

All parameters passed by reference must be labeled const.

...

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers.


In "many high quality open source projects", ideomatic C++ is not used. Many such libraries view C++ as C with a few bells and whistles added, rather than as it's own language.

Without a specific library in question though, it's difficult to say anything about use of references versus no use of references. If you're exposing a C API, then of course you're forced to use pointers, because C does not have references.


There are many reasons why code that you think would be impeccable isn't.

In the Open source arena one of the problems is that there are many people contributing there time for free with different levels of skill, so you often end up with a mish mash of styles some of which include C with classes.

In large project like dx10 the are many reasons as to why pointers are used other reference but often has a lot to with making it as easy to integrate with 'pure C' as possible; which doesn't have reference types. Or is simply a C library wrapped in a class abstraction.

Non the less just because you see 'bad' code around you is no reason to write it yourself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜