gpt4 book ai didi

c++ - C++中的 'retain state'是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:38 24 4
gpt4 key购买 nike

我在 MSDN 页面上阅读了这个解释,了解 lambda 表达式相对于仿函数和函数指针的优势。 “保持状态”的能力是什么意思?是否与在封闭范围内通过 ref 或 value 捕获某些变量的能力有关?

http://msdn.microsoft.com/en-us/library/dd293608.aspx

When writing code, you probably use function pointers and function objects to solve problems and perform calculations. Both function pointers and function objects have advantages and disadvantages: function pointers involve minimal syntactic overhead, but they do not retain state within a scope; function objects can maintain state, but they require the syntactic overhead of a class definition.

Lambda expressions are a programming technique that combines the benefits of function pointers and function objects and that avoids their disadvantages. Lambda expressions are flexible and can maintain state, just like function objects, and their compact syntax removes the need for a class definition, which function objects require. Lambda expressions enable you to write code that is less cumbersome and less prone to errors than an equivalent function object.

The following examples compare the use of a lambda expression to the use of a function object. The first example uses a lambda expression to print to the console whether each element in a vector object is even or odd. The second example uses a function object to accomplish the same task.

您能否指出一些关于范围、状态、维护状态、lambda 表达式优势的相关引用资料?

最佳答案

Functor 和 lambda 都比普通函数具有这种能力。这是在函数调用之间记住内容的能力。普通函数有静态变量,但它们是全局唯一的,如果你想要单独的函数对象有自己唯一的状态,这是不好的。这是一个仿函数类的例子:

class Counter
{
int n;
public:
Counter() :n(0) {}
int operator()() { return n++; }
};

有了这个类,我可以创建一个充当函数的实例,每次调用它时,它都会记住 n 的先前值,例如

Counter x;
cout << x() << '\n';
cout << x() << '\n';
cout << x() << '\n';

你不能用普通函数做到这一点。但是您可以使用 lambda 来做到这一点:

int n = 0;
auto x = [=]() mutable { return n++; };
cout << x() << '\n';
cout << x() << '\n';
cout << x() << '\n';

关于c++ - C++中的 'retain state'是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com