Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining volatile class object

Tags:

c++

volatile

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);
like image 756
maximus Avatar asked Jun 20 '10 04:06

maximus


People also ask

What is a volatile object?

Objects that are declared as volatile are not used in certain optimizations because their values can change at any time. The system always reads the current value of a volatile object when it is requested, even if a previous instruction asked for a value from the same object.

What is volatile object in Java?

For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.

Can we make object volatile in Java?

The volatile keyword can be used either with primitive type or objects. The volatile keyword does not cache the value of the variable and always read the variable from the main memory. The volatile keyword cannot be used with classes or methods. However, it is used with variables.

How do you declare a volatile variable in Java?

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.


2 Answers

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;
like image 195
Jesse Beder Avatar answered Oct 22 '22 05:10

Jesse Beder


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

like image 41
AviD Avatar answered Oct 22 '22 07:10

AviD