Defining volatile class object
Can the volatile be used for class objects? Like:
volatile Myclass className;
The problem is that it doesn't compile, everywhere when some method is invoked, the error says: error C2662: 'function' : cannot convert 'this' pointer from 'volatile MyClass' to 'MyCLass &'
What is the problem here and how to solve it?
EDIT:
class Queue {
private:
struct Data *data;
int amount;
int size;
public:
开发者_开发百科 Queue ();
~Queue ();
bool volatile push(struct Data element);
bool volatile pop(struct Data *element);
void volatile cleanUp();
};
.....
volatile Queue dataIn;
.....
EnterCriticalSection(&CriticalSection);
dataIn.push(element);
LeaveCriticalSection(&CriticalSection);
Yes, you can, but then you can only call member functions that are declared volatile
(just like the const
keyword). For example:
struct foo {
void a() volatile;
void b();
};
volatile foo f;
f.a(); // ok
f.b(); // not ok
Edit based on your code:
bool volatile push(struct Data element);
declares a non-volatile
member function that returns a bool volatile
(= volatile bool
). You want
bool push(struct Data element) volatile;
I think he meant to say
bool push(struct Data element) volatile;
instead of
bool volatile push(struct Data element);
Also have a look here http://www.devx.com/tips/Tip/13671
In C++ grammar, "volatile" and "const" are called "CV modifiers". That means "volatile" works in exact the same way as "const" from syntactic point of view. You can replace all "volatile" with "const" then you can understand why your code compiles or not.
Yep. We can use. Please see the modified code. I hope it should work now.
class Queue {
private:
struct Data *data;
int amount;
int size;
public:
Queue ();
~Queue ();
bool push(struct Data element) volatile;
bool pop(struct Data *element) volatile;
void cleanUp() volatile;
};
.....
volatile Queue dataIn;
.....
EnterCriticalSection(&CriticalSection);
dataIn.push(element);
LeaveCriticalSection(&CriticalSection);
精彩评论