Funciones miembro volátiles de C++


class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
    }   
};

¿Necesito declarar x y y como volatile o todas las variables miembro serán tratadas como volatile automáticamente?

Quiero asegurarme de que "stuff with x" no esté reordenado con "stuff with y" por el compilador.

EDITAR: ¿Qué sucede si estoy fundiendo un tipo normal a un tipo volatile? ¿Le indicaría esto al compilador que no reordene el acceso a esa ubicación? Quiero pasar una variable normal en una situación especial a una función cuyo parámetro es volátil. Debo ser sure compiler no reordena esa llamada con lecturas y escrituras anteriores o seguidas.

Author: ネロク, 2011-01-28

5 answers

Marcar una función miembro volatile es como marcarla const; significa que el objeto receptor se trata como si fuera declarado como volatile T*. Consecuentemente, cualquier referencia a x o y será tratada como un volatile leído en la función miembro. Además, un objeto volatile solo puede llamar a las funciones miembro volatile.

Dicho esto, es posible que desee marcar x y y volatile de todos modos, si realmente desea que todos los accesos a ellos se traten como volatile.

 28
Author: templatetypedef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-28 09:58:12

Usted no tiene que declarar las variables miembro explícitamente..

De los documentos estándar9.3.2.3,

Del mismo modo, semántica volátil (7.1.6.1) aplicar en funciones miembro volátiles al acceder al objeto y su nonstatic miembros de datos.

 7
Author: liaK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-28 10:04:05

El siguiente código:

#include <iostream>

class Bar
{
    public:

        void test();
};

class Foo
{
    public:

        void test() volatile { x.test(); }

    private:

        Bar x;
};

int main()
{
    Foo foo;

    foo.test();

    return 0;
}

Plantea un error en la compilación con gcc:

main.cpp: In member function 'void Foo::test() volatile':
main.cpp:14:33: error: no matching function for call to 'Bar::test() volatile'
main.cpp:7:8: note: candidate is: void Bar::test() <near match>

Y dado que una instancia volatile no puede llamar a un método non-volatile, podemos suponer que, sí, x y y estarán volatile en el método, incluso si la instancia de MyClass no se declara volatile.

Nota: puede eliminar el calificador volatile usando un const_cast<> si alguna vez lo necesita; sin embargo, tenga cuidado porque al igual que const hacerlo puede conducir a un comportamiento indefinido en algunos casos.

 5
Author: ereOn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-28 10:02:31

IBM implica que funciona exactamente como las funciones const.

 1
Author: Flexo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-28 09:44:14

Usando el ejemplo original:

class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
        // with no "non-volatile" optimization of the stuff done with x, y (or anything else)
    }   
    void foo() {
        // do stuff with x
        // do stuff with y
        // the stuff done with x, y (and anything else) may be optimized
    } 
};
 1
Author: ianeperson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-03 20:54:31