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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…