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 (将#修改为@)