C++ 中易失性成员函数的用途是什么?

发布于 2024-08-25 07:05:47 字数 41 浏览 3 评论 0原文

C++ 中 易失性 成员函数的用途是什么?

What is the purpose of a volatile member function in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何以笙箫默 2024-09-01 07:05:47

要回答有关“易失性成员函数”意味着什么的问题(可能是也可能不是发布问题的人最初的意图),请将成员函数标记为 const易失性(或组合的const 易失性)将这些限定符应用于函数中使用的this指针。正如标准(9.2.1“this 指针”)所述:

类 X 的成员函数中 this 的类型是 X*。如果成员函数声明为const,则this的类型为const X*,如果成员函数声明为volatile,则其类型为< code>this 是 volatile X*,如果成员函数声明为 const volatile,则 this 的类型为 const volatile X*代码>.

因此,通过将成员函数标记为易失性,您可以将该成员函数内的对象的非静态数据成员的任何访问设置为易失性

To answer the question about what it means to have a 'volatile member function' (which may or may not be what was originally intended by the person who posted the question), marking a member function as const or volatile (or a combined const volatile) applies those qualifiers to the this pointer used in the function. As stated by the standard (9.2.1 "The this pointer"):

The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.

So by marking the member function as volatile you'd be making any access to the non-static data members of the object within that member function as volatile.

放血 2024-09-01 07:05:47

编辑:

这个答案是在问题是关于 volatile 关键字时发布的。问题似乎已被第三方更改。

原文:

Volatile 通知编译器,它不应该假设刚刚放入标记为 volatile 的变量中的值在下次使用它时会存在......它必须在再次使用它之前检查当前值。

一个例子是变量是否表示可能被另一进程更改的内存位置。

这是一个示例(自从我使用 C++ 以来已经很多年了,所以请原谅任何小的语法问题):

volatile int x;

int DoSomething()
{
    x = 1;

    DoSomeOtherStuff();

    return x+1; // Don't just return 2 because we stored a 1 in x.  
                // Check to get its current value
}

EDIT:

This answer was posted when the question was about the volatile keyword. Question seems to have been changed by a third party.

ORIGINAL:

Volatile informs the compiler that it should not assume that the value it just put in the variable marked as volatile will be there next time it uses it... that it must check the current value before using it again.

One example is if the variable represents a memory location that might be changed by another process.

Here's an example (been ages since I did C++ so please forgive any minor syntax issues):

volatile int x;

int DoSomething()
{
    x = 1;

    DoSomeOtherStuff();

    return x+1; // Don't just return 2 because we stored a 1 in x.  
                // Check to get its current value
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文