Boost logo

Boost :

From: Gavin Lambert (boost_at_[hidden])
Date: 2020-04-08 01:33:17

On 8/04/2020 12:35, Jupiter wrote:
> I am doing boost local unix domain for IPC, I midified the code based
> on sample code from boost_asio/example/local/stream_server.cpp, I am a
> little bit puzzled for errors calling different async_read, if I call
> original code using shared_from_this() it works fine:
> boost::asio::async_read(this->mSocket,
> boost::asio::buffer(this->mData), boost::bind(&session::HandleRead,
> shared_from_this(), boost::asio::placeholders::error,
> boost::asio::placeholders::bytes_transferred));
> But if I tried to run a following lambda function which works in in my
> other boost asio TCP socket, it got an error "Operation canceled",
> what I could be missing here? Or do I have fundamontal problems in the
> lambda function I used for other TCP socket programs?
> boost::asio::async_read(this->mSocket,
> boost::asio::buffer(this->mData, sizeof(this->mData)), [=](const
> boost::system::error_code &status, const uint32_t size)
> {this->HandleRead(status, size);});

Your lambda isn't capturing a shared_ptr, thus if nothing else is
keeping the session object alive, it's probably being destroyed (and
cancelling the read -- though probably then also calling HandleRead
after destruction, which is bad).

You should use something like this instead:

   [self=shared_from_this()](boost::system::error_code status, size_t
size) { self->HandleRead(status, size); }

Boost list run by bdawes at, gregod at, cpdaniel at, john at