Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c++ - Copy constructor of the lambda expression

Here is a toy code with lambda:

#include <cstdio>
#include <iostream>
#include <functional>

std::function<void(int)> func(const std::function<void(int)> f) {
  return f;
}

class A {
    int x{};
    public:
    A(int a): x(a) {
      std::cout << "A::constructor
";
    }
    A(const A& obj) {
      std::cout << "A::copy_constructor
";
    }
};

int main() {
    A p(3);    
    auto lam = [p](int a){ return p;};
    func(lam);
    auto lam1(lam);
    return 0;
}

And here is the equivalent code generated by cppinsights

#include <cstdio>
#include <iostream>
#include <functional>

std::function<void (int)> func(const std::function<void (int)> f)
{
  return std::function<void (int)>(f);
}


class A
{
  int x;
  
  public: 
  inline A(int a)
  : x{a}
  {
    std::operator<<(std::cout, "A::constructor
");
  }
  
  inline A(const A & obj)
  : x{}
  {
    std::operator<<(std::cout, "A::copy_constructor
");
  }
  
};
   
int main()
{
  A p = A(3);
    
  class __lambda_22_16
  {
    public: 
    inline A operator()(int a) const
    {
      return A(p);
    }
    
    private: 
    A p;
    public: 
    // inline __lambda_22_16(const __lambda_22_16 &) noexcept(false) = default;
    // inline __lambda_22_16(__lambda_22_16 &&) noexcept(false) = default;
    __lambda_22_16(const A & _p)
    : p{_p}
    {}
    
  };
  
  __lambda_22_16 lam = __lambda_22_16{p};
  func(std::function<void (int)>(__lambda_22_16(lam)));
  __lambda_22_16 lam1 = __lambda_22_16(lam); 
  return 0;
}

The standard states:

The copy constructor and the move constructor are declared as defaulted and may be implicitly-defined according to the usual rules for copy constructors and move constructors. cppreference.com

But I don't see a copy constructor implicitly generated by the compiler for that given lambda. Could someone explain, please?

question from:https://stackoverflow.com/questions/66059461/copy-constructor-of-the-lambda-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cppinsight is not an implementation of the standard, and it doesn't magically generate all the code that a compiler would. The class that it shows for the lambda expression is such that the compiler will generate a copy constructor. Nevertheless, it gives you a hint:

// inline __lambda_22_16(const __lambda_22_16 &) noexcept(false) = default;

This is a comment, because it's not necessary to uncomment it - the compiler will do that anyhow.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...