c ++何时/为什么按值构造/销毁变量 [英] c++ When/Why are variables captured by value constructed/destroyed

查看:61
本文介绍了c ++何时/为什么按值构造/销毁变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过调用C(const C&)和〜C(),我无法理解发生了什么

I have trouble understanding what is going on here with calls to C(const C&) and ~C()

因此,我制作了一个按值捕获的lambda,然后将其返回.据我了解,每个返回的lambda都有自己的上下文(跟踪与该声明一致).

So, I make a lambda that captures by value, and then return it. As I understand, each returned lambda has it's own context (the trace is consistent with that claim).

但是,根据stroustrup的描述,lambda作为函数对象的快捷方式(在C ++第4版的11.4.1中),我希望为捕获的文件制作一个一个仅复制 变量,但事实并非如此.

However, according to stroustrup describing of lambda as a function object shortcut (in 11.4.1 of C++ 4th ed), I would expect one copy only to be made for the captured variable, and it does not seem to be the case.

这是我的代码

//g++  5.4.0
#include <functional>
#include <iostream>
using namespace std;

class C{
    float f; 
  public:
    C(float f): f(f){ cout << "#build C(" << f << ")\n"; }
    C(const C& c): f(c.f+0.1){ cout << "#copy C(" << f << ")\n"; }
    ~C(){ cout << "#destroy C(" << f << ")\n"; }
    void display() const { cout << "this is C(" << f << ")\n"; }
};

std::function<void(void)> make_lambda_val(int i){
    C c{i};
    return [=] () -> void { c.display(); } ;
}

int main(){
    cout << "/**trace\n\n";
    cout << "---  ??  ---\n";
    {
        auto l0 = make_lambda_val(0);
        auto l1 = make_lambda_val(1);
        auto l2 = make_lambda_val(2);
        cout << "ready\n";
        l0();
        l1();
        l2();
    }
    cout << "\n*/\n";
}

以及相应的跟踪记录:(带有我的评论)

and the corresponding trace: (with my comment)

/**trace

---  ??  ---
#build C(0)
#copy C(0.1)     <<--|  2 copies ??
#copy C(0.2)     <<--|  
#destroy C(0.1)  <----  one of which is already discarded ?
#destroy C(0)
#build C(1)
#copy C(1.1)
#copy C(1.2)
#destroy C(1.1)
#destroy C(1)
#build C(2)
#copy C(2.1)
#copy C(2.2)
#destroy C(2.1)
#destroy C(2)
ready
this is C(0.2)   <---- the second copy is kept ?
this is C(1.2)
this is C(2.2)
#destroy C(2.2)
#destroy C(1.2)
#destroy C(0.2)

*/

推荐答案

我希望捕获的变量只能复制一份

I would expect one copy only to be made for the captured variable

实际上捕获的变量被复制一次.也就是说,它仅是复制操作中的源.

And indeed the captured variable is copied once. That is, it's the source in a copy operation only once.

std :: function 不是lambda.它的初始化涉及复制可调用对象.因此,当将 lambda 复制到 std :: function 时,其按值保存的变量也将被复制.当函数返回时,lambda临时文件将被销毁.您将看到在您创建的lambda内部变量的破坏.

A std::function is not a lambda. Its initialization involves copying the callable object. So when the lambda is copied into the std::function, the variable it holds by value is copied as well. And when the function returns, the lambda temporary is destoryed. What you see is the destruction of the variable inside the lambda you created.

这篇关于c ++何时/为什么按值构造/销毁变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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