Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7960637
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T04:48:43+00:00 2026-06-04T04:48:43+00:00

C++11 lambdas are great! But one thing is missing, which is how to safely

  • 0

C++11 lambdas are great!

But one thing is missing, which is how to safely deal with mutable data.

The following will give bad counts after the first count:

#include <cstdio>
#include <functional>
#include <memory>

std::function<int(void)> f1()
{
    int k = 121;
    return std::function<int(void)>([&]{return k++;});
}

int main()
{
    int j = 50;
    auto g = f1();
    printf("%d\n", g());
    printf("%d\n", g());
    printf("%d\n", g());
    printf("%d\n", g());
}

gives,

$ g++-4.5 -std=c++0x -o test test.cpp && ./test
121
8365280
8365280
8365280

The reason is that after f1() returns, k is out of scope but still on the stack. So the first time g() is executed k is fine, but after that the stack is corrupted and k loses its value.

So, the only way I’ve managed to make safely returnable closures in C++11 is to allocate closed variables explicitly on the heap:

std::function<int(void)> f2()
{
    int k = 121;
    std::shared_ptr<int> o = std::shared_ptr<int>(new int(k));
    return std::function<int(void)>([=]{return (*o)++;});
}

int main()
{
    int j = 50;
auto g = f2();
    printf("%d\n", g());
    printf("%d\n", g());
    printf("%d\n", g());
    printf("%d\n", g());
}

Here, [=] is used to ensure the shared pointer is copied, not referenced, so that memory handling is done correctly: the heap-allocated copy of k should be freed when the generated function g goes out of scope. The result is as desired,

$ g++-4.5 -std=c++0x -o test test.cpp && ./test
121
122
123
124

It’s pretty ugly to refer to variables by dereferencing them, but it should be possible to use references instead:

std::function<int(void)> f3()
{
    int k = 121;
    std::shared_ptr<int> o = std::shared_ptr<int>(new int(k));
    int &p = *o;
    return std::function<int(void)>([&]{return p++;});
}

Actually, this oddly gives me,

$ g++-4.5 -std=c++0x -o test test.cpp && ./test
0
1
2
3

Any idea why? Maybe it’s not polite to take a reference of a shared pointer, now that I think about it, since it’s not a tracked reference. I found that moving the reference to inside the lambda causes a crash,

std::function<int(void)> f4()
{
    int k = 121;
std::shared_ptr<int> o = std::shared_ptr<int>(new int(k));
    return std::function<int(void)>([&]{int &p = *o; return p++;});
}

giving,

g++-4.5 -std=c++0x -o test test.cpp && ./test
156565552
/bin/bash: line 1: 25219 Segmentation fault      ./test

In any case, it would be nice if there was a way to automatically make safely returnable closures via heap allocation. For example, if there was an alternative to [=] and [&] that indicated that variables should be heap allocated and referenced via references to shared pointers. My initial thought when I learned about std::function was that it creates an object encapsulating the closure, therefore it could provide storage for the closure environment, but my experiments show that this doesn’t seem to help.

I think safely returnable closures in C++11 are going to be paramount to using them, does anyone know how this can be accomplished more elegantly?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T04:48:45+00:00Added an answer on June 4, 2026 at 4:48 am

    In f1 you’re getting undefined behavior for the reason you say; the lambda contains a reference to a local variable, and after the function returns the reference is no longer valid. To get around this you don’t have to allocate on the heap, you simply have to declare that captured values are mutable:

    int k = 121;
    return std::function<int(void)>([=]() mutable {return k++;});
    

    You will have to be careful about using this lambda though, because different copies of it will be modifying their own copy of the captured variable. Often algorithms expect that using a copy of a functor is equivalent to using the original. I think there’s only one algorithm that actually makes allowances for a stateful function object, std::for_each, where it returns another copy of the function object it uses so you can access whatever modifications occurred.


    In f3 nothing is maintaining a copy of the shared pointer, so the memory is being freed and accessing it gives undefined behavior. You can fix this by explicitly capturing the shared pointer by value and still capture the pointed-to int by reference.

    std::shared_ptr<int> o = std::shared_ptr<int>(new int(k));
    int &p = *o;
    return std::function<int(void)>([&p,o]{return p++;});
    

    f4 is again undefined behavior because you’re again capturing a reference to a local variable, o. You should simply capture by value but then still create your int &p inside the lambda in order to get the syntax you want.

    std::shared_ptr<int> o = std::shared_ptr<int>(new int(k));
    return std::function<int(void)>([o]() -> int {int &p = *o; return p++;});
    

    Note that when you add the second statement C++11 no longer allows you to omit the return type. (clang and I assume gcc have an extension that allows return type deduction even with multiple statement, but you should get a warning at least.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How do you deal with lambdas in boo? Is callable the same thing? How
I'm trying to figure out Python lambdas. Is lambda one of those "interesting" language
I need to write the following SQL statement in LINQ lambdas : SELECT *
I have a custom sort routine that works great, but I was curious about
i just started to learn coffeescript and it's great, but it's tricky.. i try
Ok I have the following, set-up and working great. These lines of code should
When I debug and/or run it on my develop machine it works great, but
I've been following with great interest the converstaion here: Construct Query with Linq rather
I currently have the following code which allows me to call any method required
Can lambdas be defined as data members? For example, would it be possible to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.