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?
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?
a + b + c
supposed to do, leak memory?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With