1

In this boost asio example I see:

auto self(shared_from_this()); //boost::shared_ptr<connection>

boost::asio::async_write(socket_, reply_.to_buffers(),
    [this, self](boost::system::error_code ec, std::size_t)
    {
        //...
    }
);

In Visual Studio 2015, if I write

[this, shared_from_this()](boost::system::error_code ec, std::size_t)

I receive the following error:

Error C2059 syntax error: ')'

Why can't the lambda function capture the boost::shared_ptr variable directly from the call to the shared_from_this()? Isn't it the same thing? I can't find anywhere an explanation. I've read other examples (e.g. this or this, but they don't ask this question).

Community
  • 1
  • 1
Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46
  • 2
    Try using the correct syntax for named captures: `[this, self=shared_from_this()]( ... )` – Sam Varshavchik Dec 06 '16 at 01:54
  • This actually compiles successfully, but it still doesn't make sense for me. In your example, `self` is not declared (like in the example `auto self(shared_from_this())`), so how does the lambda know its type? – Alexandru Irimiea Dec 06 '16 at 01:59
  • 1
    The lambda uses the type `auto` for named captures, the same type you used in an explicit declaration. Named types use `auto`, and the compiler figures out the type from the expression that's used to initialize it. – Sam Varshavchik Dec 06 '16 at 02:01
  • OK, you can add this as an aswer so I can upvote it. – Alexandru Irimiea Aug 29 '17 at 17:21

1 Answers1

2

The correct syntax for named captures, in your case, would be:

[this, self=shared_from_this()]( ... ) 
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148