C++ operator overloading for pointers

拈花ヽ惹草 提交于 2019-11-29 14:39:28

True, the rvalue reference solution is even better, as that allows stack-based objects, while this overloading would force all Vector2d objects to live on the heap, but still, it seems to be something that would have been easy to implement in compilers, possibly years before rvalue refs came around. And with custom allocators, it wouldn't even be that slow.

So is this only illegal because of the "least surprise" principle, or are there other reasons too?

  • It doesn't chain properly... what's a + b + c supposed to do, leak memory?
  • Pointer arithmetic already has a meaning in C++... it's useful for that to be consistent across types, otherwise e.g. algorithms wouldn't work properly on containers of your objects.
  • Returning something by value implies that object doesn't need clean up by the caller: if it uses free store (heap) to store actual data, it'll be deleting it automatically as necessary. Makes consistently robust memory usage easier.

Note how 'a + b' creates a new Vector object, but then copies only its address into 'c', without calling a copy constructor. So it would sort of solve the same problem that the new rvalue references solve.

The commonly implemented Return Value Optimisation also addressed this problem, helping the compiler arrange for construction of the return value directly into the caller's buffer.

The main reason is because pointers already have a certain number of operators defined for them. If I have two variables a and b of type MyType, and I write a - b, then the reader knows that he has to look for an overload or an implicit conversion. If the variables have type MyType*, the reader would probably assume that a - b is pointer arithmetic; having it mean something else would be confusing, and would probably cause problems where ever arrays of MyType occur (including in the internals of std::vector).

Similar considerations apply to many of the other operators. The guideline in C++ is that you should be able to extend the language, but not change it. (And I know that unary & is an exception to this rule.)

With regards to C#, the languages are different. In C#, pointers aren't objects; there is no distinction between MyType and MyType*, and there are no operators on pointers. And C# doesn't use value semantics (usually), where as most objects in C++ will have value semantics, and will practically never be dynamically allocated. (If Vector2d means what it seems to mean, it should never be allocated dynamically in C++.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!