tags:

views:

36

answers:

1

How would I catch a member variable by value when using C++0x lambdas?

Using the [=my_member] syntax doesn't seem to work, and implicit capture uses the "this" pointer. What is need is a way to explicitly specify capture type of member variables. Is that possible?

My workaround for now is:

void member_function()
{
    std::shared_ptr<my_member_class> my_member_copy = my_member; // this shouldn't be necessary
    std::async([=]{ std::cout << *my_member_copy; });
    // std::async([=]{ std::cout << *my_member_; }); // wrong, my member could be potentially out of scope
}

EDIT: Clearified question

+1  A: 

I don't think you can capture a member by value, you can capture this but since the member is part of this you'll be using a shared member and not a new variable.

Not knowing what type your member is something like this should work:

auto copy = my_member;
std::async([copy]{ std::cout << copy; });

I don't understand why you're using a shared_ptr in your example, if you want to capture by value surely shared_ptr is the last thing you should consider.

Motti
I need to capture by value inorder for the shared_ptr ref count to be incremented. Otherwise the object will be destroyed when the parent object is destroyed, thus causing a potential access violation in the async operation. (forgot to add * in the lambda).I don't see how you example differs from mine.
ronag
"Not knowing what type your member is something like this should work:", the reason i wrote std::shared_ptr instead of auto was to be explicit about the type of "my_member", that is shared_ptr<my_member_class>.
ronag