Unused captured var in lambda

I

Igor R.

Hello,

I'm trying to convert some parts of a legacy code to use c++0x
lambdas. The original line looks like this:
someQueue_->post(bind(&MyClass::func, shared_from_this()));

When converting, I certainly have to keep the "binding" with
shared_ptr. I intend to do this as follows:
auto self = shared_from_this();
someQueue_->post([&, self] {func()});

However, my concern is that the captured but unused "self" may be
omitted by c++ compiler during the optimization. I'd appreciate if
someone familiar with the relevant specs could shed some light on
this.


Thanks.
 
S

SG

I'm trying to convert some parts of a legacy code to use c++0x
lambdas. The original line looks like this:
someQueue_->post(bind(&MyClass::func, shared_from_this()));

When converting, I certainly have to keep the "binding" with
shared_ptr. I intend to do this as follows:
auto self = shared_from_this();
someQueue_->post([&, self] {func()});

Why don't you simply write

[=]{self->func();}

here?
However, my concern is that the captured but unused "self" may be
omitted by c++ compiler during the optimization. I'd appreciate if
someone familiar with the relevant specs could shed some light on
this.

That's an interesting question. I've never thought about that.
According to the current draft section 5.1.2:

Paragraph 10:
"...An entity (i.e. a variable or this) is said to be explicitly
captured if it appears in the lambda-expression’s capture-list...

Paragraph 12:
...An entity is captured if it is captured explicitly or
implicitly. ..."

So, it sounds like by explicitly mentioning a variable in the capture
lits it is guaranteed to be captured even if it is not used in its
body. At least that's my interpretation.

Cheers!
SG
 
I

Igor R.

Why don't you simply write
  [=]{self->func();}

here?

Well, you're right, in such a trivial case this would be the best
solution, but I'm wondering about more general case where there are
captured shared_ptr's, which really cannot be used inside the lambda.
According to the current draft section 5.1.2:

Paragraph 10:
  "...An entity (i.e. a variable or this) is said to be explicitly
   captured if it appears in the lambda-expression’s capture-list....

Paragraph 12:
   ...An entity is captured if it is captured explicitly or
   implicitly. ..."

So, it sounds like by explicitly mentioning a variable in the capture
lits it is guaranteed to be captured even if it is not used in its
body. At least that's my interpretation.

Great! Thanks a lot.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top