Pointers or references?
-
Stroustrup is against using references for a passed parameter when a function changes the reference's content as well. I don't know -- I have gone back and forth on this in my own code. I still tend to like references better since it gets rid of all the pointer dereferencing inside my functions. Better for the function writer, not as good for the function user. C# probably does have the advantage of hindsight on this issue. CodeGuy The WTL newsgroup: over 1100 members! Be a part of it. http://groups.yahoo.com/group/wtl
I learned C++ using that Stroustrup's ideas on references too. And like you, I go back and forth on the passing modified arguments via reference. But most of the time, modified arguments end up being by pointer and non-modified end up with a NICE FAT "const". Tim Smith Descartes Systems Sciences, Inc.
-
It is all a question of style. Don't believe this junk about pointers being bad. Like everything, bad programmers will always find ways of screwing up good things. But some people have made some very good points about references. Here are the rules I use. 1. If the argument is read-only, pass by const reference. 2. If the argument is read-write, pass by pointer and sometimes a reference. 3. If the argument is write-only, pass by pointer. The reason is purely based on style. The idea is that by making an argument that will be written to a pointer, you are providing a hint that the value will be modified. IMHO, it is poor style to pass arguments that will be modified by reference. Some very good points I have seen from other people. 1. A reference can not be NULL. Well, this isn't 100% true, but in the real world it is. MyFunc (*(MyClass *) NULL)) is an example of how you can fake it out. However, the programmer had to do work to do that and thus should be shot on site!!! (EDIT: LOL, ... shot on sight.) 2. When passing by reference, there isn't the ambiguity that a pointer is pointing to one or an array of elements. But, you shouldn't be passing an array by pointer without the size of the array being supplied. Tim Smith Descartes Systems Sciences, Inc.
1. A reference can not be NULL. Well, this isn't 100% true, but in the real world it is. MyFunc (*(MyClass *) NULL)) is an example of how you can fake it out. However, the programmer had to do work to do that and thus should be shot on site!!! (EDIT: LOL, ... shot on sight.) To the best of my knowledge, the statement that a reference cannot be
NULL
is 100% true. Dereferencing the null pointer as in(*(MyClass *) NULL)
is explicitly marked by the standard as undefined behavior. You cannot rely on this line of code passing unnoticed in run time for every C++ compiler. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo -
Beleiving that reference always "points" to something is NOT dangerous, coding like this is dangerous:
Bar* pBar=NULL; Foo(*pBar);
James (2b || !2b)James Pullicino wrote: Beleiving that reference always "points" to something is NOT dangerous, coding like this is dangerous: Yes of course it's dangerous. But if you asume that a caller is smart enough not to write code like that than you could also asume that a caller is smart enough not to pass a NULL pointer. What I want to point out is that you can pass an invalid ref. Nobody prevents you from doing that. In the same way nobody prevents you from passing a NULL pointer. So I don't see there any reasons to asume a ref is valid just because it's a ref whereas you always (hopefully) check for NULL pointers. CU Max
-
Or code like this: CTimbuktoo::Foo( *pToSomethingReallyImportant ) { m_pX = pToSomethingReallyImportant; } CBumPhuckEgypt::AnotherFoo( *pToSomethingReallyImportant ) { m_pX = pToSomethingReallyImportant; } Where m_pX is a public variable in both cases. What a nightmare...
Stan Shannon wrote: CBumPhuckEgypt Laughed my fucking arse off at that one. I think the whole function declaration is worthy of signature status. Will have to see if I have the energy to change mine. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone
-
I learned C++ using that Stroustrup's ideas on references too. And like you, I go back and forth on the passing modified arguments via reference. But most of the time, modified arguments end up being by pointer and non-modified end up with a NICE FAT "const". Tim Smith Descartes Systems Sciences, Inc.
I dunno -- I still tend toward readability in my own programs, which I think pointers detract from. I think Stroustrup writes from the perspective of large-scale software design, in which you may have a lot of other people reading and using your interfaces, libraries, etc. If that is the case, you probably want to give people as many clues as possible as to what your functions are doing. For programming-in-the-small, I put the pointers/references in the same arena as Get/Set methods for public member variables. (OO heresy! :) ) I've just have never had a debugging issue arise where the pointers vs. references issue made an impact. CodeGuy The WTL newsgroup: over 1100 members! Be a part of it. http://groups.yahoo.com/group/wtl
-
They're not exactly the same, because references enforce an additional constraint that pointers do not, namely with references you cannot pass a "null" object (typically represented by the null pointer). So my rationale for deciding between the two styles is:
- If the parameter can be "void" and this is well represented by the null pointer, use pointers.
- In any other case, use references.
Joaquín M López Muñoz Telefónica, Investigación y Desarrollo
You forgot to mention that references cannot be "reseated", that is, you can't change the entity the reference "points" to. Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook
-
When deciding whether to use pointers or references as function parameters, remember this: When passing by reference, the parameter is garanteed to be a valid (existing) object, when passing by pointer, it is not. Therefore whenever possible pass by reference since: - you'll produce safer code - no validation of the object is required - easier to code (no -> and *x = 10 etc...) - compiler will catch incorrect type casts When it is not possible, pass by pointer and understand the dangers. James (2b || !2b)
James Pullicino wrote: the parameter is garanteed to be a valid (existing) object, This is true when everybody is playing by the rules. It is possible to have "null" references and references to invalid objects, but this is an abomination and the person responsible should be put to a slow and painful death. :) Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook
-
I dunno -- I still tend toward readability in my own programs, which I think pointers detract from. I think Stroustrup writes from the perspective of large-scale software design, in which you may have a lot of other people reading and using your interfaces, libraries, etc. If that is the case, you probably want to give people as many clues as possible as to what your functions are doing. For programming-in-the-small, I put the pointers/references in the same arena as Get/Set methods for public member variables. (OO heresy! :) ) I've just have never had a debugging issue arise where the pointers vs. references issue made an impact. CodeGuy The WTL newsgroup: over 1100 members! Be a part of it. http://groups.yahoo.com/group/wtl
-
S. Spenz wrote: I think pointers look much better than this ugly & I do not think that this is a question of aesthetics ;) S. Spenz wrote: Of course sometimes you have no choice but if what would you choose? I really like declarations such as
void foo (const bar& x);
. This is safe, you cannot even changex
accidentally. Regards Thomas Finally with Sonork id: 100.10453 Thömmi
Disclaimer:
Because of heavy processing requirements, we are currently using some of your unused brain capacity for backup processing. Please ignore any hallucinations, voices or unusual dreams you may experience. Please avoid concentration-intensive tasks until further notice. Thank you.Thomas Freudenberg wrote: void foo (const bar& x);. I got used to put the modifiers (const, volatile) to the right of the type as I find it easier to read (and understand). I would express your example as
void foo(bar const& x); // Notice the const after the typename
I found out that reading declarations from right to left is easier. e.g.
void foo(char const* p); // 1) Read as "p is a pointer to a constant char"
void foo(char* const p); // 2) Read as "p is a constant pointer to a char"
void foo(char* const* p); // 3) Read as "p is a pointer to a constant pointer to a char"- Means that the contents of the object pointed by p cannot be modified (using p) 2) Means that p cannot be changed to point to another object. 3) Means that neither contents of the object pointed by p can be modified nor the object to which p points to. Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook
-
1. A reference can not be NULL. Well, this isn't 100% true, but in the real world it is. MyFunc (*(MyClass *) NULL)) is an example of how you can fake it out. However, the programmer had to do work to do that and thus should be shot on site!!! (EDIT: LOL, ... shot on sight.) To the best of my knowledge, the statement that a reference cannot be
NULL
is 100% true. Dereferencing the null pointer as in(*(MyClass *) NULL)
is explicitly marked by the standard as undefined behavior. You cannot rely on this line of code passing unnoticed in run time for every C++ compiler. Joaquín M López Muñoz Telefónica, Investigación y DesarrolloHere is the direct quote from the standard: [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which cases undefined behavior...] Thus my statement that it isn't 100% true, but in the real world it is. The standard makes no requirement that a reference can not exist. It just says that in a well-defined program it can not exist since the construct required to do it would by definition make a program not well-defined. (IMHO: We are splitting hairs here) Tim Smith Descartes Systems Sciences, Inc.
-
Nish [BusterBoy] wrote: Well sometimes you might want to modify the passed pointer. Modifying the passed a pointer within the function actually has no effect to the caller. Therefore you could write the following:
void Foo(Bar& bar)
{
Bar* pBar=&bar;
pBar=&SomethingElseForWhatEverReason;
}instead of
void Foo(Bar* pBar)
{
pBar=&SomethingElseForWhatEverReason;
}But to be honest I'm not really a fan of references. Beleiving that a reference always "points" to something is dangerous:
Bar* pBar=NULL;
//...
Foo(*pBar);So I don't see there a big advantage in using refs. Should we start another religious war? ;P CU Max
But to be honest I'm not really a fan of references. Beleiving that a reference always "points" to something is dangerous: Not true at all. The only way to do this gets you into the realm of undefined behavior and thus is inherently bad programming. Tim Smith Descartes Systems Sciences, Inc.
-
Stan Shannon wrote: CBumPhuckEgypt Laughed my fucking arse off at that one. I think the whole function declaration is worthy of signature status. Will have to see if I have the energy to change mine. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone
Thanks, Mick. I thought that was fairly discriptive of some of the code I've had to work on in my lifetime. The biggest problem with pointers is that they give lazy programmers the power to be lazy and get away with it. How's the job search going? If you are still unemployed then you and I are now in the same boat. Except that I just up and quit my job. I intend to spend two or three months living off my savings, mooching off my wife, and upgrading my skills a bit then trying the job market again. I might end up flipping burgers for the rest of my career, and raising my kids as trailer trash, but I've just finally had it with the bad management and unrealistic expectations that pervade the software industry. I think if I can't get something going on my own, I am going to get completely out of the business.
-
Here is the direct quote from the standard: [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which cases undefined behavior...] Thus my statement that it isn't 100% true, but in the real world it is. The standard makes no requirement that a reference can not exist. It just says that in a well-defined program it can not exist since the construct required to do it would by definition make a program not well-defined. (IMHO: We are splitting hairs here) Tim Smith Descartes Systems Sciences, Inc.
(IMHO: We are splitting hairs here) Sure we are! That's the fun of it ;) Take this lightly, it's obvious that we both know exactly what we're talking bout. So, to continue with this exercise of exegesis, you seem to state that the standard does not say
a reference to a null object cannot exist
but instead it says
a reference to a null object cannot exist in a well-defined program.
So the standard implies that
references to null objects can only exist in badly-defined programs.
Now I'm curious as to what a "well-defined" program is (is it the same as a correct program?) Cheers! Joaquín M López Muñoz Telefónica, Investigación y Desarrollo
-
Thanks, Mick. I thought that was fairly discriptive of some of the code I've had to work on in my lifetime. The biggest problem with pointers is that they give lazy programmers the power to be lazy and get away with it. How's the job search going? If you are still unemployed then you and I are now in the same boat. Except that I just up and quit my job. I intend to spend two or three months living off my savings, mooching off my wife, and upgrading my skills a bit then trying the job market again. I might end up flipping burgers for the rest of my career, and raising my kids as trailer trash, but I've just finally had it with the bad management and unrealistic expectations that pervade the software industry. I think if I can't get something going on my own, I am going to get completely out of the business.
Stan Shannon wrote: How's the job search going? Sat on my arse for the last 2 months and prettty much did fuck all. Had My, Mother In-law, Wifes, Father In-laws and Daughters birthdays in that time so did a lot of preparing and entertaining. Got no savings so spending myself further into debt. Though I did spend a couple of weeks in a factory, the manual non-thinking work was good for a change. Would be doing it now as they came back this week but I have a spasming muscle in my back. Physio trying to fix it now. Have just finished version 0.11 of my résumé and have sent it to a couple of close friends for perusal. After that I will post a link here in the lounge for pointers to get it as shiny as possible and then it's serious job hunting time. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone
-
You forgot to mention that references cannot be "reseated", that is, you can't change the entity the reference "points" to. Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook
Eddie Velasquez wrote: Foot-and-Mouth disease is believed to be the first virus unable to spread through Microsoft Outlook Its close relative, Foot in Mouth disease, does not appear to have this limitation.
-
(IMHO: We are splitting hairs here) Sure we are! That's the fun of it ;) Take this lightly, it's obvious that we both know exactly what we're talking bout. So, to continue with this exercise of exegesis, you seem to state that the standard does not say
a reference to a null object cannot exist
but instead it says
a reference to a null object cannot exist in a well-defined program.
So the standard implies that
references to null objects can only exist in badly-defined programs.
Now I'm curious as to what a "well-defined" program is (is it the same as a correct program?) Cheers! Joaquín M López Muñoz Telefónica, Investigación y Desarrollo
Joaquín M López Muñoz wrote: Now I'm curious as to what a "well-defined" program is (is it the same as a correct program?) Obviously, a well-defined program is a program, where no references to null objects exist. ;P Regards Thomas Finally with Sonork id: 100.10453 Thömmi
Disclaimer:
Because of heavy processing requirements, we are currently using some of your unused brain capacity for backup processing. Please ignore any hallucinations, voices or unusual dreams you may experience. Please avoid concentration-intensive tasks until further notice. Thank you. -
What do you like more in your code? Functions with pointers or references parameters? I don't talk about required e.g. API function stuff but about self-defined functions. I think pointers look much better than this ugly & ;) . Of course sometimes you have no choice but if what would you choose? ----------------------------------------- I'm a signature virus. Copy me to your sig and help me spread...
S. Spenz wrote: What do you like more in your code? Functions with pointers or references parameters? Here is a small often overlooked thought: Consider that you are building a DLL for external use by others. Do you use pointers or references in your parameter lists? (Possible reason why you should not: the C++ standard says that the implementation of references is implementation-dependent, meaning depending largly on you compiler suite, correct? So what happens when code generated with one compiler tries to use code generated by another? Like Borland <-> CV++, or VC++ <-> MinGW?) Peace! -=- James.
-
S. Spenz wrote: What do you like more in your code? Functions with pointers or references parameters? Here is a small often overlooked thought: Consider that you are building a DLL for external use by others. Do you use pointers or references in your parameter lists? (Possible reason why you should not: the C++ standard says that the implementation of references is implementation-dependent, meaning depending largly on you compiler suite, correct? So what happens when code generated with one compiler tries to use code generated by another? Like Borland <-> CV++, or VC++ <-> MinGW?) Peace! -=- James.
If only references were the greatest problem in intercompiler communication! (sigh) Unfortunately (or not?), there's an enormous set of implementation details due to wich which code generated by two compilers can not be mixed. To name a few: name mangling, member function calling convention, class layout, virtual table implementation... Reference implementation is but a tiny drop of water in the middle of this ocean of incompatibilities. In case you're interested, there's some effort going on on different forums about the problem of defining a compiler interoperable C++ Aplication Binary Interface. Lots of info on the net, just type "C++ ABI" in your favorite search engine. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo
-
Stan Shannon wrote: How's the job search going? Sat on my arse for the last 2 months and prettty much did fuck all. Had My, Mother In-law, Wifes, Father In-laws and Daughters birthdays in that time so did a lot of preparing and entertaining. Got no savings so spending myself further into debt. Though I did spend a couple of weeks in a factory, the manual non-thinking work was good for a change. Would be doing it now as they came back this week but I have a spasming muscle in my back. Physio trying to fix it now. Have just finished version 0.11 of my résumé and have sent it to a couple of close friends for perusal. After that I will post a link here in the lounge for pointers to get it as shiny as possible and then it's serious job hunting time. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone
-
Stan Shannon wrote: How's the job search going? Sat on my arse for the last 2 months and prettty much did fuck all. Had My, Mother In-law, Wifes, Father In-laws and Daughters birthdays in that time so did a lot of preparing and entertaining. Got no savings so spending myself further into debt. Though I did spend a couple of weeks in a factory, the manual non-thinking work was good for a change. Would be doing it now as they came back this week but I have a spasming muscle in my back. Physio trying to fix it now. Have just finished version 0.11 of my résumé and have sent it to a couple of close friends for perusal. After that I will post a link here in the lounge for pointers to get it as shiny as possible and then it's serious job hunting time. Michael Martin Australia mmartin@netspace.net.au "Don't belong. Never join. Think for yourself. Peace" - Victor Stone
Michael Martin wrote: then it's serious job hunting time Sorry, I am still not available to attend interviews for you :-D Roger Allen Sonork 100.10016