When would I use const volatile, register volatile, static volatile in C++?

前端 未结 1 1836
傲寒
傲寒 2020-12-07 17:16

I am wondering about the different uses of the volatile keyword in combination with register, const and static

相关标签:
1条回答
  • 2020-12-07 18:09
    register volatile int T=10;
    

    volatile qualifier means that the compiler cannot apply optimizations or reorder access to T, While register is a hint to the compiler that T will be heavily used. If address of T is taken, the hint is simply ignored by the compiler. Note that register is deprecated but still used.

    Practical Usage:

    I have never used it never felt the need for it and can't really think of any right now.


    const volatile int T=10;
    

    const qualifier means that the T cannot be modified through code. If you attempt to do so the compiler will provide a diagnostic. volatile still means the same as in case 1. The compiler cannot optimize or reorder access to T.

    Practical Usage:

    • Accessing shared memory in read-only mode.
    • Accessing hardware registers in read-only mode.

    static volatile int T=10;
    

    static storage qualifier gives T static storage duration (C++11 §3.7) and internal linkage, while volatile still governs the optimization and reordering.

    Practical Usage:

    • Same as volatile except that you need the object to have static storage duration and to be inaccessible from other translation units.
    0 讨论(0)
提交回复
热议问题