According to Bjarne Stroustrup, references were introduced into C++ to support operator overloading:
References were introduced primarily to support operator overloading.
C passes every function argument by value, and where passing an object by value would be inefficient or inappropriate the user can pass a pointer. This strategy doesn't work where operator overloading is used. In that case, notational convenience is essential because users cannot be expected to insert address-of operators if the objects are large. For example:
a = b - c;
is acceptable (that is, conventional) notation, but
a = &b - &c;
is not. Anyway, &b - &c
already has a meaning in C, and I didn't want to change that.
Having both pointers and references in the language is a constant source of confusion for C++ novices.
Couldn't Bjarne have solved this problem by introducing a special language rule that allowed object arguments to decay into pointers if a user-defined operator function exists that takes such pointers?
The declaration and usage of subtraction would then have looked like:
Foo operator-(const Foo* x, const Foo* y);
a = b - c;
Was such a solution ever proposed/considered? Would there be any serious downsides to it?
Yes I know, references provide other advantages due to their restrictions, but that's not the point.
Interestingly, the assignment operator of C with classes seems to have worked exactly like that:
Changing the meaning of assignment for objects of a class [...] is done by declaring a class member function called operator=
. For example:
class x {
public:
int a;
class y * p;
void operator = (class x *);
};
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…