[英]Position of volatile keyword in member function declaration in C++
Does the positioning of the 'volatile' keyword in a method declaration affect its functionality? 方法声明中'volatile'关键字的位置是否会影响其功能?
ie, is there any difference between the following two pieces of code? 即,以下两段代码之间有什么区别吗?
A. 一种。
class Test
{
public:
volatile void testMe()
{
}
};
B. B.
class Test
{
public:
void testMe() volatile
{
}
};
And same goes when the member function has a return value. 当成员函数具有返回值时,也是如此。 Thank you!
谢谢!
It is the same as for the const
qualifier. 与
const
限定符相同。
In the first example, the volatile
applies to the return value of the function. 在第一个示例中,
volatile
适用于函数的返回值。 It is void in this case, so it doesn't make much sense. 在这种情况下,它是无效的,因此没有太大意义。 In fact, it doesn't make much sense to return by volatile value * .
实际上,返回volatile值*并没有多大意义。 A volatile return type would only make sense for a reference:
可变返回类型仅对引用有意义:
volatile int& foo() { ... }
volatile int& i = foo(); // OK
int j = foo(); // OK, use the volatile reference to construct a non volatile int
int& j = foo(); // Error!
In the second case, it means that the method is volatile
, hence it can be called on (non-const) non-volatile and volatile instances of class Test
. 在第二种情况下,这意味着,该方法是
volatile
的,因此它可以在(非const)类的非易失性和易失性实例调用Test
。 A similar method without the volatile
qualifier could not be called on a volatile
instance. 没有
volatile
限定符的类似方法无法在volatile
volatile
实例上调用。
Test test0;
test0.testMe(); // OK
volatile Test test1;
test1.testMe(); // OK
test1.someNonVolatileMethod(); // Error.
* Unless that value is a pointer *除非该值是一个指针
The same rules that apply to const
apply to volatile
. 适用于
const
的相同规则也适用于volatile
。
When returning void
(rather not returning), volatile
is useless in the first snippet. 当返回
void
(而不是不返回)时, volatile
在第一个代码段中是无用的。
The second snippet marks the whole method as volatile
. 第二个片段将整个方法标记为
volatile
。
For example, if you have: 例如,如果您有:
volatile Test m;
m.testMe();
only compiles is testMe
is marked as volatile
(like your second code). 仅将
testMe
标记为volatile
(如第二个代码)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.