简体   繁体   English

C ++ lambda两个复制构造函数调用

[英]C++ lambda two copy constructor calls

I have the following code snippet. 我有以下代码片段。

#include <iostream>
#include <functional>
using namespace std;

struct A
{
    A() { cout << "A "; data = 1; }
    A(const A& a) { cout << "cA "; data = a.data; }
    ~A() { cout << " dA"; }
    int data;
};

void f(A& a, function<void(A)> f)
{
    cout << "(";
    f(a);
    cout << ")";
}

int main()
{
    A temp;
    auto fun = [](A a) {cout << a.data;};
    f(temp, fun);
}

The output is: 输出是:

A (cA cA 1 dA dA) dA A(cA cA 1 dA dA)dA

Why is temp copied twice? 为什么temp复制两次?

I am using Visual C++ (vc140). 我使用的是Visual C ++(vc140)。

function<void(A)> has a function-call operator with this signature: operator()(A) ie it takes its argument by value, so calling f(a) makes a copy. function<void(A)>有一个带有此签名的函数调用运算符: operator()(A)即它按值​​获取其参数,因此调用f(a)进行复制。

The lambda also takes its argument by value, so when that is called inside the function<void(A)> call operator another copy gets made. lambda也通过值获取其参数,因此当在function<void(A)> call function<void(A)>内部调用它时,会生成另一个副本。

If you define a move constructor for A you should see that initializing the lambda argument (from the first copy made by the function ) can be a move instead of a copy, but only if the type has a move constructor. 如果为A定义移动构造函数,则应该看到初始化lambda参数(来自function的第一个副本)可以是移动而不是副本,但仅当类型具有移动构造函数时才可以。 Otherwise it has to be copied. 否则必须复制。

Alternatively, if you use std::function<void(const A&)> then the call operator will take its argument by reference not by value, so there is only one copy made, to initialize the argument of the lambda. 或者,如果使用std::function<void(const A&)>则调用操作符将通过引用而不是值来获取其参数,因此只有一个副本用于初始化lambda的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM