|
|
|
|
|
by bff
6032 days ago
|
|
There is a precise term for that and you said it - pass-by-value. Recall that somewhere each language turns into assembly and that in order to pass a value to a subroutine you must either place values into registers or push the data of the object you are passing onto the stack. Passing by value is desirable if you want to make sure that your local value is not modified. This gives the called function the freedom to modify it without worrying about side effects and without worrying about explicitly calling a copy constructor. Pass-by-reference comes from C++'s pass by reference, which is really just some sugar around passing a pointer by value and referencing it with the * operator in the function body (hence reference passing). I disagree that there is a right or wrong to this - C++ was made to be a generic programming language and thus gives many options to the programmer. If by "do it right" you meant "hide all options except the one most commonly used" okay. Otherwise I strongly disagree with that sentence especially because I use different kinds of "pass-by" whenever I program in C++ and will be using rvalue reference from the C++0x. Different languages suit different needs. |
|
vector<int> numbers; void f(vector<int> args);
Due to C++'s copying, args[0] has a different address than numbers[0], because a deep copy of the vector was made. As the article states, this is not what pass-by-value is referring to, otherwise it would be false that Java / Python / Ruby et al are pass-by-value. So I disagree that the terms are clear, but rather that there is confusion around these terms. As for wanting immutability, it's almost always better for C++ code to write functions not like f but instead like this:
void g(const vector<int>& args);
And apologies for the editorializing, but I do consider this a language design flaw, one inherited from the backwards compatibility for C, which already allowed struct's to be passed (non-pointer) as args and then copied to keep the caller untouchable. It makes C++ code more verbose and more error prone, and is quite difficult for new programmers to grasp.