我要从Lambda返回引用,为什么会发生复制? [英] I'm Returning a Reference From a Lambda, why is a Copy Happening?

查看:66
本文介绍了我要从Lambda返回引用,为什么会发生复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的答案引起了我的注意,我认为lambdas是通过引用返回的.例如,如果我们定义它:

It's been brought to my attention by the answer to this question that lambdas I thought were returning by reference are copying. If we define this for example:

struct A {
    A() = default;
    A(const A&) { cout << "copy\n"; }
};

此代码均未调用副本构造函数:

None of this code calls the copy constructor:

A a;
const A* pa = &a;
const A& ra = *pa;

但是此代码在返回时调用复制构造函数:

But this code calls the copy constructor on return:

[](const A* pa){ return *pa; }(pa);

在线示例

我不明白.为什么要复印回来?或更笼统地说,我想我应该问:"lambda如何决定如何返回?"

I don't get it. Why is it returning by copy? Or more generally I guess I should ask: "How does a lambda decide how to return?"

推荐答案

lambda的返回类型为 auto ( [expr.prim.lambda]/4 ),因此除非您使用尾随返回类型明确指定它,否则将进行复制:

The return type of a lambda is auto ([expr.prim.lambda]/4), so a copy will be made unless you explicitly specify it with the trailing return type:

[](const A* pa) -> const auto& { return *pa; }(pa);

这篇关于我要从Lambda返回引用,为什么会发生复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆