什么是“不可检测的手段"?以及它们如何更改C/C ++程序的对象? [英] What are "undetectable means" and how can they change objects of a C/C++ program?

查看:71
本文介绍了什么是“不可检测的手段"?以及它们如何更改C/C ++程序的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ISO/IEC 14882:2003(C ++ 03)在7.1.5.1/8中的"​​cv限定词"部分中作了规定:

In ISO/IEC 14882:2003 (C++03) is stated under 7.1.5.1/8, section "The cv-qualifers":

[注:volatile是实现的一种暗示,以避免涉及对象的强烈优化,因为对象的值可能通过实现无法检测到的方式进行更改.有关详细语义,请参见1.9.通常,volatile的语义在C ++中的意图与在C语言中是相同的.]

[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. ]


这些方法"在实施中无法检测到,已经成为Nawaz问答的主题.为什么我们使用volatile关键字:

但是,有时候,(对程序的某些部分)进行优化可能是不可取的,因为可能是其他人从程序外部更改了some_int的值,而编译器并未意识到这一点 ,因为它看不到;但这就是您设计的方式.在这种情况下,编译器的优化将无法产生预期的结果!

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!

但是不幸的是,他没有解释这些可能从程序外部更改对象的方法"的含义,以及它们如何更改对象.

But unfortunately, he missed to explain what these "means", that may change objects from outside the program, can be and how they can change objects.

我的问题:

  • 这些无法检测的手段"有哪些例子?它们如何能够从程序外部更改程序的内部对象?

推荐答案

同一程序或其他程序的其他部分可能会看到内存中的指针.例如,存在于共享内存中的变量可以被另一个程序更改.

A pointer in memory may be visible by other parts of the same or another program. For example, a variable that exists in shared memory and can be changed by another program.

编译器无法检测到.

其他示例是基于硬件的内存位置.

Other examples are hardware-based memory locations.

通常,需要易变变量的应用通常会处理诸如异步音频之类的问题,并且在系统级别处理中断,APIC等.大多数应用都不需要它们.

Generally, apps that need volatile variables usually deal with stuff like asynchronous audio, and at the system level, interrupts, APIC etc. Most apps do not need them.

一个假想的例子:

int v = 0;

// Some thread
SetUpdatesOn(&v);

 // Another thread
for(;;)
{
   int g = v;
   std::cout << g;
}

假定虚构的OS级函数SetUpdatesOn定期更改传递给它的变量.如果未将变量声明为volatile,则编译器可能会优化int g = v调用或假定v始终具有相同的值.

Assume that an imaginary OS-level function SetUpdatesOn periodically changes the variable passed to it. If the variable is not declared volatile, the compiler might optimize the int g = v call or assume that v always has the same value.

如果将变量声明为volatile,则编译器将继续在循环中读取它.

If the variable is declared volatile, the compiler will keep reading it in the loop.

请注意,通常很难调试此类编程错误,因为优化可能仅存在于发行版中.

Note that very often it is difficult to debug such programming mistakes because the optimization may only exist in release builds.

这篇关于什么是“不可检测的手段"?以及它们如何更改C/C ++程序的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆