Could operator overloading have worked without references?

前端 未结 5 1923
孤街浪徒
孤街浪徒 2020-12-17 00:07

According to Bjarne Stroustrup, references were introduced into C++ to support operator overloading:

References were introduced primarily to support o

5条回答
  •  抹茶落季
    2020-12-17 00:24

    If you accept that doing it with pointers (either implicitly or explicitly) would introduce really confusing semantics (am I operating on the pointer or the pointee?) then without references that only leaves call by value. (Besides your Foo c = &b - &a; example consider the case where you wanted to write an operator that really did use a pointer as one of it's arguments)

    I don't think pointers without & at the call site is usefully-workable and certainly no better than references. If you make it a special feature of operators and only operators then that moves the behaviour well into the "cryptic" special case realm. If you want to reduce the "special case" aspect of it by making it a general feature then I don't think it's helpful or useful over the call by reference as it stands.

    For example if I want to write an operator that takes a Foo and a void* I can write:

    Foo operator+(const Foo& f, void *ptr);
    

    Under your proposed rules that would become: Foo operator+(Foo *f, void *ptr);. The problem as I see it would then be that even though I wanted ptr to explicitly be a pointer by the "implict & rule" it would accept anything and there doesn't seem to be a way for me to disallow the automatic conversion. So double d; Foo f; f = f + d; would match that, as would int i; Foo f; f = f + i;, potentially in two different ways!

    Call by value might have worked and made sense for "simple" types, and you could use smart pointers for the cases where you really don't want to have to take a copy of each operand. In general though the idea of being forced to copy everything seems very unclean compared to a reference based approach.

提交回复
热议问题