Mendes
Mendes

Reputation: 18541

C++ boost::asio how to properly use std::shared_ptr on async functions

This is my first project with boost::asio and I´m building an async server.

I need to use a shared_ptr to control access to the session control pointer. Here is the way I´m doing to define the session and pass it to the boost async function:

// Define the new session object
std::shared_ptr<SocketSession> session = std::make_shared<SocketSession>(ioService);

// Configure the acceptor
acceptor.async_accept(session->getSessionSocket(),
                      boost::bind(&SocketServer::HandleAccept, 
                      this, 
                      session, 
                      boost::asio::placeholders::error));

And the handler signature:

void SocketServer::HandleAccept(std::shared_ptr<SocketSession> session,
                                const boost::system::error_code& errorCode)

The code compile fine, not errors at all. But on running the code, the HandleAccept method is called with an error: Operation canceled, not even listening to the socket.

It seens that this is related to the way I´m using shrared_ptr. I´ve gone through some examples and boost uses shared_from_this. I can´t find out why is that necessary, and why my shared_ptr fail at runtime.

Help appreciated.

Note: This code is running on ther server class (Server), not on the session class (SocketSession). In my view this lead not to use shared_from_this as SocketSession is being created at another object....

Upvotes: 1

Views: 1517

Answers (1)

sehe
sehe

Reputation: 393769

@Mendez I have several introductory samples when people ran into the requirement for this "ASIO pattern".

You could look at them, because I do explain the pattern and why it's introduced:

Upvotes: 2

Related Questions