well. Code could look like this:
class Vector3 {
static some_lock_type the_lock;
public:
float x, y, z;
float const & operator[](unsigned int i) const {
SomeLockAcquiringWrapper the_guard ( the_lock );
static float Vector3::* const proxy[3] =
{ &Vector3::x, &Vector3::y, &Vector3::z };
return (*this).*proxy[i];
}
float & operator[] ( unsigned int i ) {
return
( const_cast<float&>
( const_cast<Vector3 const *>(this)->operator[](i) ) );
}
};
However, it might be to costly to do that :-(
Your static array is const but you cast away the const-ness with your
non-const operator[], so clients would be free to try to change the
contents with potentially lethal results.
No, they can't even try: the const_cast is not applied to the static
object "proxy" at any time, it is applied to the object for which the
member function operator[] is called. That does not propagate to static
members. Nobody, at any time, can change the pointer-to-member entries in
proxy.
However, if you feel uncomfortable using the harmless const_cast<> trick,
you can easily rewrite the whole thing equivalently as follows:
#include <cassert>
#include <cstddef>
class Vector3 {
static
float Vector3::* const
proxy ( std::size_t i ) {
static float Vector3::* const the_proxy [3] =
{ &Vector3::x, &Vector3::y, &Vector3::z };
return ( the_proxy[i] );
}
public:
float x, y, z;
float const & operator[] ( std::size_t i ) const {
assert( i < 3 );
return (*this).*(proxy(i));
}
float & operator[] ( std::size_t i ) {
assert( i < 3 );
return (*this).*(proxy(i));
}
};
#include <iostream>
int main ( void ) {
Vector3 a;
a[1] = 2;
std::cout << a.y << '\n';
}
The use of locking will, of
course, get you around the data corruption issue, but I doubt clients
of the class would be expecting to pay the penalty of locking just to
access a class like this. I certainly wouldn't.
I still don't see any data corruption issue. Could you present a scenario,
in code, where it might happen.
Best
Kai-Uwe Bux
Ah, thanks for your patience. I had not properly read the previous
postings and was incorrect in my statements. See my other recent post
solution. :)