新聞中心
本篇內(nèi)容主要講解“C++中使用volatile有什么作用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C++中使用volatile有什么作用”吧!
創(chuàng)新互聯(lián)公司從2013年開始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務公司,擁有項目網(wǎng)站制作、成都網(wǎng)站制作網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元安岳做網(wǎng)站,已為上家服務,為安岳各地企業(yè)和個人服務,聯(lián)系電話:028-86922220
CP.200:使用volatile只能表明該變量是非C++內(nèi)存
Reason(原因)
volatile is used to refer to objects that are shared with "non-C++" code or hardware that does not follow the C++ memory model.
volatile用于表明參照的對象需要和非C++代碼或硬件共享而遵守C++內(nèi)存模型。
Example(示例)
const volatile long clock;
這段代碼描述一個不斷被時鐘電路更新的寄存器。clock被定義為volatile是因為它的值在使用它的C++程序沒有任何動作的情況下被修改。例如,兩次讀取clock經(jīng)??梢缘玫讲煌闹?,因此優(yōu)化器最好不要優(yōu)化掉這段代碼中的第二個讀操作。
long t1 = clock;
// ... no use of clock here ...
long t2 = clock;
clock is const because the program should not try to write to clock.
clock定義為常量是為了表明程序不應該對clock進行寫操作。
Note(注意)
Unless you are writing the lowest level code manipulating hardware directly, consider volatile an esoteric feature that is best avoided.
除非你正在編寫直接操作硬件的低層次代碼,否則將volatile作為冷門功能并最好避免使用。
Example(示例)
Usually C++ code receives volatile memory that is owned elsewhere (hardware or another language):
通常情況下,C++代碼接受有其他某處擁有的volatile內(nèi)存(硬件或其他語言):
int volatile* vi = get_hardware_memory_location();
// note: we get a pointer to someone else's memory here
// volatile says "treat this with extra respect"
某些C++代碼會分配volatile內(nèi)存并通過故意泄露指針的方式和其他部分共享(硬件或其他語言)它。
static volatile long vl;
please_use_this(&vl); // escape a reference to this to "elsewhere" (not C++)
Example, bad(反面示例)
volatile類型的局部變量幾乎一定是錯的--如果它們只能短期存在,怎么能分享給其他語言或硬件呢?由于同樣的原因,該原則也幾乎一定適用于成員變量。
void f()
{
volatile int i = 0; // bad, volatile local variable
// etc.
}
class My_type {
volatile int i = 0; // suspicious, volatile member variable
// etc.
};
Note(注意)
In C++, unlike in some other languages, volatile has nothing to do with synchronization.
和其他語言不同,在C++中不會為同步做任何事情。
Enforcement(實施建議)
Flag volatile T local and member variables; almost certainly you intended to use atomic
instead. 標記volatile類型的局部變量和成員變量;幾乎可以肯定的說你想用的其實是atomatic
。
到此,相信大家對“C++中使用volatile有什么作用”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!
文章題目:C++中使用volatile有什么作用
網(wǎng)頁路徑:http://fisionsoft.com.cn/article/jiepso.html