0
#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.

6
  • 1
    You called New. You didn't call the lambda. Also, C is not C++. Commented Apr 2, 2017 at 2:24
  • Also, you're leaking everything you allocate. Commented Apr 2, 2017 at 2:25
  • Here what I mean is I will wipe off the method1 if I select method. Could you give me more some details? Commented Apr 2, 2017 at 2:34
  • @Ryan, compiler give me a error is : there no such convertable funtion from "lambda []int ()->int" to "int" Commented Apr 2, 2017 at 2:36
  • You didn't call the lambda. Commented Apr 2, 2017 at 2:38

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I just write this small instance in haste, and will care more by ur note.
0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.