$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [Boost-users] [Asio]Question about error_code when socket::close
From: Comet (cometliao_at_[hidden])
Date: 2010-05-17 06:29:59
> That is because you are most likely using the inefficient creation
> style, probably like this:
>   shared_ptr<myClass> myPtr(new myClass(arg1,arg2));
> Which will also new a struct inside the shared_ptr that holds that
> pointer and bookkeeping information. If you have read the shared_ptr
> documentation, the efficient creation style is this:
>   shared_ptr<myClass> myPtr = make_shared<myClass>(arg1,arg2);
> Which will new both your class and the bookkeeping information in the
> same place in memory, increasing both the speed of creation (only one
> new), and speed of accessing (better cache coherency).
> When creating your objects at the same time (literally) as the
> shared_ptr, that should fix most of those speed issues.
That's not the point, make_shared can be used only when the object is
created,but what I said is as follows:
class Session
: public boost::enable_shared_from_this<Session> {
 public:
  static void HandleRead(boost::weak_ptr<Session> session,
                         const boost::system::error_code& error,
                         size_t bytes_transferred) {
    if (session.expired())
      return;
    ...
  }
  void Read() {
    // this line is very slow, 
    // because boost::bind(&Session::HandleRead,shared_from_this(), ...)
    // causes extra new/delete operations
    socket_.async_read_some(boost::asio::buffer(...),
                            boost::bind(&Session::HandleRead,
                                        shared_from_this(),
                                        _1, _2));
    ...
  }
  void Close() {
    socket_.close();
  }
 private:
  boost::asio::ip::tcp::socket  socket_;
};
std::set<boost::shared_ptr<Session> > session_set;
  boost::shared_ptr<Session> session
      = boost::make_shared<Session>();
  session_set.insert(session);
  session->Read();
  ....
  session->Close();
  session_set->erase(session); // session is destroyed here,
if I replace 
static void HandleRead(weak_prt ...) with void HandleRead(...) 
and 
boost::bind(&Session::HandleRead, shared_from_this()...), with
boost::bind(&Session::HandleRead, this, ...);
the question I asked emerges:
void HandleRead(const boost::system::error_code& error,
                size_t bytes_transferred) {
    if (error) 
      //should I erase shared_from_this() from session_set? this object
may have been destroyed...
  }
  ....
  session->Close();
  session_set->erase(session); // session is destroyed here. if I don't
do this here, where should I do ? HandleRead may not be registered
ever...