I've been having a lot of trouble over the last couple of days with operator overloading.
Basically, I'm designing a Vector3 class and I need to be able to do things like vector1 - vector2 in any class I use them without having to expand everything out every time. The problem I'm having is that I can't get it working with my multi-threading as the functions aren't thread safe. I'll show you what I've got:
But that causes compiler error C2678: binary '+' : no operator found which takes a left-hand operand of type 'const Vector3' (or there is no acceptable conversion).
This has really been driving me nuts. Any help would be greatly appreciated!
First, lets get rid of a misconception
v.x += 2;
v.y += 3;
is just as thread unsafe as
v = vector( v.x + 2, v.y + 3 );
Unless you are looking at specific compiler intrinsics, no c++ operation is atomic, not even "x += 2;".
Secondly, you shouldn't worry about your vector class being thread unsafe. You need to be insuring thread safety at a higher level. Whatever classes are touching shared vectors need to be locking before doing so.
Thread-safety cannot be achieved to any meaningful conceptual degree at this level.
Simply put: it doesn't make sense.
Question is about "atomicity". When viewed from outside, do individual operations, such as + or add behave as if they are atomic - they cannot be interrupted in the middle.
Atomicity doesn't make much sense here either - due to composition, associativity and other rules, which part of "(a+b)*(c+b)" needs to be atomic? The additions? The multiplication? The whole equation?
The common solution to above problems is immutability and treating vectors as constant scalar types. Such solution is guaranteed to be conceptually sane, but carries considerable performance cost (see string class in .Net or Java for examples, or Haskell, Erlang for general design).
In practice, one simply doesn't worry about thread-safety inside such classes, but instead requires caller to be aware of library being thread-unaware and have them arrange data in such a way that it's not a problem.
Subtle issues, either with design or implementation performance are what keeps STM models from seeing much use with traditional (C/C++/Java/...) languages.
It might be the case that these are currently returning references to automatic or temporary variables, which is going to cause trouble sooner or later.
Quite apart from thread-safety, the following probably shouldn't return references, but Vector3 objects by value:
It might be the case that these are currently returning references to automatic or temporary variables, which is going to cause trouble sooner or later.
Yeah, I had the same idea, but as soon as I changed it to return by value, I started getting linker errors telling me that the functions were already defined. Really weird stuff
Alright, sorted it. I ended up using unary overloads, which I'd tried originally but weren't working. I/m not sure what I did differently, but it seems fine, now.