By value or by reference?
Jacek Generowicz
jacek.generowicz at cern.ch
Wed Oct 20 05:11:26 EDT 2004
aleaxit at yahoo.com (Alex Martelli) writes:
> Jacek Generowicz <jacek.generowicz at cern.ch> wrote:
> ...
> > Here's a program that tells you the answer. Should be trivially
> > translatable to many other languages.
> >
> > ========================================================================
> > def passCheck(b):
> > b = 'new'
> >
> > def doesThisLanguageBindByValue(language):
> > a = 'original'
> > b = a
> > b = 'new'
> > if a == 'original':
> > print "%s assigns by value" % (language)
> > else:
> > print "%s does not assigns by value" % (language)
>
> Can you give some examples of languages which would end up in the else
> branch?
Sure. Here it is in C++:
========================================================================
#include <iostream>
#include <string>
void passCheck(std::string& b) {
b = "new";
}
void doesThisBindByValue() {
std::string a = "original";
std::string& b = a;
b = "new";
if (a == "original") {
std::cout << "by value" << std::endl;
} else {
std::cout << "NOT by value" << std::endl;
}
a = 1;
passCheck(a);
if (a == "original") {
std::cout << "by value" << std::endl;
} else {
std::cout << "NOT by value" << std::endl;
}
}
int main() {
doesThisBindByValue();
return 0;
}
========================================================================
> I think that with a suitably perverse operator= I might be able
> to imitate this weird effect in C++, but then I think I'd have to make
> the 'b = a' a copy ctor instead of an assignment (or get to such levels
> of perversion that even my once-C++-addled mind reels at...;-).
No need for such horrors. Just declare the variables to be references
... and then you really do get bind-by-reference. It does exactly what
is says on the tin (unusual for C++, I know :-).
More information about the Python-list
mailing list