挥发性功能 [英] Volatile function

查看:139
本文介绍了挥发性功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要:这是什么关键字挥发性当C和C ++中应用到函数声明呢?

Summary: What does the keyword volatile do when applied to a function declaration in C and in C++?

详细信息

我看到它是可以通过编译标记为函数挥发性。但是,我不知道是什么编译器优化(如果有的话),这个prevents。比如我创建了以下测试案例:

I see that it's possible to compile a function that is marked as volatile. However, I'm not sure what compiler optimization (if any) this prevents. For instance I created the following test case:

volatile int foo() {
  return 1;
}

int main() {
  int total = 0;
  int i = 0;
  for(i = 0; i < 100; i++) {
    total += foo();
  }

  return total;
}

当我编译铛-emit-LLVM -S -O3 test.c以(GCC也将工作,但LLVM IR更具可读性在我看来),我得到

When I compile with clang -emit-llvm -S -O3 test.c (gcc would also work but the llvm IR is more readable in my opinion) I get:

target triple = "x86_64-unknown-linux-gnu"

define i32 @foo() #0 {
  ret i32 1
}

define i32 @main() #0 {
  ret i32 100
}

所以,很显然,编译器能够优化掉的调用函数富()的main()返回一个常量,即使富()标记为挥发性。所以我的问题是,是否挥发性做任何事情时,在限制编译器优化方面应用到函数声明。

So obviously the compiler was able to optimize away the calls to function foo() so that main() returns a constant, even though foo() is marked as volatile. So my question is whether volatile does anything at all when applied to a function declaration in terms of limiting compiler optimizations.

(注意:我对这个问题的兴趣主要是好奇明白什么挥发性确实,而不是解决任何特定的问题。)

(Note my interest in this question is mostly curiosity to understand what volatile does rather than to solve any specific problem.)

(我也标志着这个问题,因为C和C ++并不是因为我认为他们是同一种语言,而是因为我想知道是否有什么挥发性确实在这种情况下,这两种语言)。

(Also I have marked this question as both C and C++ not because I think they are the same language, but because I am interested to know if there are differences in what volatile does in this case in these two languages).

推荐答案

在您的code时,挥发性关键字不适用的功能,但对返回类型,它是等价的:

In your code, the volatile keyword does not apply to the function, but to the return type, it is the equivalent of:

typedef volatile int Type;
Type foo();

现在,在C ++中,你可以做一个的成员的函数挥发性,以同样的方式,在常量预选赛,并且行为是一样的:

Now, in C++ you can make a member function volatile, in the same way that the const qualifier, and the behavior is the same:

struct test {
   void vfunction() volatile;
};

基本上你不能调用类型的挥发性(分别为常量)实例非易失性(alterantively非const)功能:

Basically you cannot call a non-volatile (alterantively non-const) function on a volatile (const respectively) instance of the type:

struct test {
   void vfunction() volatile;
   void function();
};
volatile test t;
t.vfunction();      // ok
t.function();       // error

这篇关于挥发性功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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