By value or by reference?

Alex Martelli aleaxit at
Wed Oct 20 11:50:51 CEST 2004

Jacek Generowicz <jacek.generowicz at> wrote:
> > > 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++:
>   std::string  a = "original";
>   std::string& b = a;

Ah, references, of course.  And you need to make the two "b =" bits
drastically different in meaning, taking advantage of the fact that C++
overloads = to mean both initialization/construction and assignment;
that's not quite cheating but it sure bends the rules;-).

And after all this, the message "C++ does not assign by value" is false,
because it sure does, under many (most!-) circumstances.  You'd need to
rephrase this as "under at least some circumstances, C++ does assign
not-by-value" or the like.

To remove the need to bend the rules, and have both "b =" be
assignments, you do need a peculiar type for b, such as (untested and
I'm rusty in C++, so take it w/a grain of salt):

class sly {
    std::string *p;
    sly() { p=0; }
    std::string& operator=(std::string& x) {
        if(p) (*p)=x;
        else p=&x;

Here, the first assignment to b (declared as 'sly b;') follows the else
branch of operator=, initializing p; following ones follow the if
branch, altering whatever p is holding on to.
((Not sure operator= as written will accept an '= "new";' assignment,
but if not that could be easily cured by overloading operator= with a
variant taking a const std::string&)).

OK, so there are languages which have reference-variables or let you
build such beasts -- as I recall the first one was Algol 68.  But
"(language) does not assign by value" should be true only for languages
that do NOT assign by value, as opposed to ones which may have several
kinds of assignments...


More information about the Python-list mailing list