什么是 "undetectable means" 以及它们如何更改 C/C++ 程序的对象?
What are "undetectable means" and how can they change objects of a C/C++ program?
在 ISO/IEC 14882:2003 (C++03) 中,在 7.1.5.1/8 部分 "The cv-qualifers":
中说明
[Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. ]
这些 "means" 无法被实现检测到的也已经成为 Nawaz 问答的主题 Why do we use volatile keyword:
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
但不幸的是,他没有解释这些 "means" 可能会从程序外部更改对象,以及它们如何更改对象。
我的问题:
- 这些 "undetectable means" 的示例是什么?它们如何能够从程序外部更改程序的内部对象?
内存中的指针可能对同一程序或另一个程序的其他部分可见。例如,一个变量存在于共享内存中,可以被另一个程序更改。
编译器无法检测到。
其他示例是基于硬件的内存位置。
一般来说,需要 volatile 变量的应用程序通常处理异步音频、系统级中断、APIC 等内容。大多数应用程序不需要它们。
一个想象的例子:
int v = 0;
// Some thread
SetUpdatesOn(&v);
// Another thread
for(;;)
{
int g = v;
std::cout << g;
}
假设一个虚构的 OS 级函数 SetUpdatesOn
周期性地改变传递给它的变量。如果变量未声明为 volatile,编译器可能会优化 int g = v
调用或假设 v
始终具有相同的值。
如果变量被声明为 volatile,编译器将在循环中继续读取它。
请注意,通常很难调试此类编程错误,因为优化可能仅存在于发布版本中。
在 ISO/IEC 14882:2003 (C++03) 中,在 7.1.5.1/8 部分 "The cv-qualifers":
中说明[Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. ]
这些 "means" 无法被实现检测到的也已经成为 Nawaz 问答的主题 Why do we use volatile keyword:
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
但不幸的是,他没有解释这些 "means" 可能会从程序外部更改对象,以及它们如何更改对象。
我的问题:
- 这些 "undetectable means" 的示例是什么?它们如何能够从程序外部更改程序的内部对象?
内存中的指针可能对同一程序或另一个程序的其他部分可见。例如,一个变量存在于共享内存中,可以被另一个程序更改。
编译器无法检测到。
其他示例是基于硬件的内存位置。
一般来说,需要 volatile 变量的应用程序通常处理异步音频、系统级中断、APIC 等内容。大多数应用程序不需要它们。
一个想象的例子:
int v = 0;
// Some thread
SetUpdatesOn(&v);
// Another thread
for(;;)
{
int g = v;
std::cout << g;
}
假设一个虚构的 OS 级函数 SetUpdatesOn
周期性地改变传递给它的变量。如果变量未声明为 volatile,编译器可能会优化 int g = v
调用或假设 v
始终具有相同的值。
如果变量被声明为 volatile,编译器将在循环中继续读取它。
请注意,通常很难调试此类编程错误,因为优化可能仅存在于发布版本中。