如何解决C++ 闭包行为
我想确保我了解 C++ 中的闭包如何在“幕后”工作,因此我编写了一个程序 (Visual Studio 2019) 来详细查看行为:
#include <iostream>
#include <iomanip>
#include <functional>
#include <list>
using namespace std;
class A
{
list<int> ints = { 1,2 };
void display(string msg) const {
cout << setw(8) << msg << ": this = 0x" << this << ",ints.front() = " << ints.front() << endl;
}
public:
A() { ints.front() += 1; display("A()"); }
A(const A& other) : ints(other.ints) { ints.front() += 1; display("A(A&)"); }
A(const A&& other) noexcept : ints(other.ints) { ints.front() += 1; display("A(A&&)"); }
~A() { display("~A()"); }
void doSomething() const { display("A doing something"); }
};
function<void (void)> fn()
{
A a;
auto rfn = [=]() {
cout << "In Lambda: &a = 0x" << &a << endl;
a.doSomething();
};
return rfn;
}
int main()
{
{
auto fn2 = fn();
fn2();
}
return 0;
}
当我运行这个时,我得到了以下输出:
A(): this = 0x010FF948,ints.front() = 2
A(A&): this = 0x010FF934,ints.front() = 3
A(A&&): this = 0x010FF838,ints.front() = 4
A(A&&): this = 0x010FFA4C,ints.front() = 5
~A(): this = 0x010FF838,ints.front() = 4
~A(): this = 0x010FF934,ints.front() = 3
~A(): this = 0x010FF948,ints.front() = 2
In Lambda: &a = 0x010FFA4C
A doing something: this = 0x010FFA4C,ints.front() = 5
~A(): this = 0x010FFA4C,ints.front() = 5
我可以理解第一个复制构造函数,但是两个右值引用构造函数调用让我感到困惑。为什么需要它们?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。