Typecast operator overloading

I have an array A of T *, and I want to make sure that A[0] is never used without locking the mutex M, while changing as little code as possible.
What I thought was writing a wrapper class:
1
2
3
4
5
class A_check{
    T *data;
    bool check;
//...
};

I need to cover a few cases, such as A[0]->foo, T *p=A[0], and a[0]=p.
Will these two overloads cover the last two cases as I expect?
1
2
operator T *() const{ return this->data; }
operator T *&(){ return this->data; }

Any suggestions (better methods, etc.)?
Also operator[]
Nah, I know I won't need that one. The pointers point to single objects and it's known that they can't point to arrays.
So wait.... where would you unlock the mutex in all of this?

And do you need to lock access to the object or to the pointer?

I'm not really seeing how the code you posted would work at all -- maybe I'm misunderstanding the problem.
And do you need to lock access to the object or to the pointer?
The pointer.

So wait.... where would you unlock the mutex in all of this?
This code doesn't actually lock the mutex. It just verifies that it's locked. It's used only for debugging. The mutex is locked and unlocked whenever the pointer needs to be used, which is why I need to make sure I didn't forget anything.

I'm not really seeing how the code you posted would work at all
That's because I omitted the checks. I just wanted to give the general idea of what I was trying to do.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class DEBUG_MUTEX_T{
	T *data;
	bool check_mutex;
public:
	DEBUG_MUTEX_T():data(0),check_mutex(0){}
	T *operator=(T *p){ return this->data=p; }
	void force_mutex_check(){ this->check_mutex=1; }
	operator T *() const{
		if (this->check_mutex && !mutex.is_locked())
			throw std::string("mutex is unlocked.");
		return this->data;
	}
	operator T *&(){
		if (this->check_mutex && !mutex.is_locked())
			throw std::string("mutex is unlocked.");
		return this->data;
	}
	T *operator->() const{
		if (this->check_mutex && !mutex.is_locked())
			throw std::string("mutex is unlocked.");
		return this->data;
	}
};
//usage:
#ifndef DEBUG_MUTEX
T *array[4];
#else
DEBUG_MUTEX_T array[4];
#endif
array[0]=//...
#ifdef DEBUG_MUTEX
array[0].force_mutex_check();
#endif

mutex.lock();
array[0]->foo=bar; //OK
mutex.unlock();

std::cout <<array[0]->foo<<std::endl; //possible race condition! 


By the way, I used a trick to make sure every lock is paired with an unlock:
1
2
3
4
5
6
7
8
9
10
11
12
class MutexLocker{
	Mutex &mutex;
	MutexLocker(const MutexLocker &m):mutex(m.mutex){}
	void operator=(const MutexLocker &){}
public:
	MutexLocker(Mutex &m):mutex(m){
		this->mutex.lock();
	}
	~MutexLocker(){
		this->mutex.unlock();
	}
};
Last edited on
Topic archived. No new replies allowed.