Reputation: 401
#include<iostream>
using namespace std;
int* New()
{
return new int(666);
}
int Foo()
{
//method1:
int* it = New();
return *it;
//method2:
return []() { return *(new int(666)); };//Complier has a complain here
/*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/
}
int main()
{
cout << Foo() << endl;
return 0;
}
I'm fresh in C++, I encounter a situation above, I had review the chapter 10.3.2 to 10.3.3 of C++ Primer, where introduces the lambda expression.But it doesn't work for me, I'm also confused about the last annotation I list.
Upvotes: 0
Views: 77
Reputation: 401
Actuall, I didn't call my lambda because it lacks the call operator. So, I fix it as:
return []() { return *(new int(666)); }();
It works now.
I review the words from Chapter of 10.3.2 of C++ Primer "We call a lambda the same way we call funtion by using the call operator".
Upvotes: 0
Reputation: 34563
return []() { return *(new int(666)); };
This line is trying to return the lambda itself. You want to call the lambda and return the integer that it produces:
return []() { return *(new int(666)); }(); // Note the () at the end
There's generally not much point in defining a lambda function only to immediately call it, though. They're more commonly used when you need to actually return a function, or take one as an argument. (This is a more advanced thing to do, though, so you probably shouldn't worry about it for now.)
On a separate note: your program allocates integers with new
, but it never releases them with delete
. This is a memory leak, which is something you should avoid.
Upvotes: 2