Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator overloading for pointers

I wonder (just out of curiosity) why operator overloading isn't allowed in C++ for pointers. I mean something like this:

Vector2d* operator+(Vector2d* a, Vector2d* b) { return new Vector2d(a.x + b.x, a.y + b.y); }

Vector2d* a = new Vector2d(1, 1); 
Vector2d* b = new Vector2d(2, 2); 
Vector2d* c = a + b; 

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. Also, as far as I know, it's pretty much equivalent to what happens when using operator overloading in C# (but I might be wrong here, I've never actually used C#), and why rvalue refs are not necessary in C#.

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?

like image 932
imre Avatar asked Jan 13 '23 16:01

imre


1 Answers

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.

like image 105
Tony Delroy Avatar answered Jan 23 '23 17:01

Tony Delroy