P
pauldepstein
My texts give plenty of examples where passing by reference is
necessary. For instance, the famous swap example.
However, I've never seen an example where passing a variable by value
is necessary.
One place where I've seen passing by value recommended is in the
throwing of exceptions. However, my texts never say why throwing by
reference is wrong. (Of course, lots of people have explained why
catching by value is poor practice.) Suppose I did throw by reference
using namespace std; and including the correct exceptions libraries.
Could I then write:
throw &runtime_error("Incorrect...blah blah ");
Or would this code be incorrect? My thinking is that a runtime_error
is initialized with the string "Incorrect...blah blah " and that a
reference to that error is thrown.
Can anyone give a link to or give an example where the technique of
passing by value is necessary to make a function work, and where
passing by reference would lead to problems.
I see two reasons to sometimes pass by value (not sure if this is
correct). 1) Passing by value is quicker for simple built-in types
like int. 2) Passing by value is easier to code (though the greater
ease probably only makes a difference to beginners.)
This doesn't seem enough of a reason for the language to include the
passing-by-value concept.
Are there reasons not to pass everything by value?
Thank you for your explanations.
Paul Epstein
necessary. For instance, the famous swap example.
However, I've never seen an example where passing a variable by value
is necessary.
One place where I've seen passing by value recommended is in the
throwing of exceptions. However, my texts never say why throwing by
reference is wrong. (Of course, lots of people have explained why
catching by value is poor practice.) Suppose I did throw by reference
using namespace std; and including the correct exceptions libraries.
Could I then write:
throw &runtime_error("Incorrect...blah blah ");
Or would this code be incorrect? My thinking is that a runtime_error
is initialized with the string "Incorrect...blah blah " and that a
reference to that error is thrown.
Can anyone give a link to or give an example where the technique of
passing by value is necessary to make a function work, and where
passing by reference would lead to problems.
I see two reasons to sometimes pass by value (not sure if this is
correct). 1) Passing by value is quicker for simple built-in types
like int. 2) Passing by value is easier to code (though the greater
ease probably only makes a difference to beginners.)
This doesn't seem enough of a reason for the language to include the
passing-by-value concept.
Are there reasons not to pass everything by value?
Thank you for your explanations.
Paul Epstein