Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7520417
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T02:04:01+00:00 2026-05-30T02:04:01+00:00

The sample I’m looking at in full is: #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/enable_shared_from_this.hpp>

  • 0

The sample I’m looking at in full is:

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <vector>

using boost::asio::ip::tcp;

// A reference-counted non-modifiable buffer class.
class shared_const_buffer
{
public:
  // Construct from a std::string.
  explicit shared_const_buffer(const std::string& data)
    : data_(new std::vector<char>(data.begin(), data.end())),
      buffer_(boost::asio::buffer(*data_))
  {
  }
  // Implement the ConstBufferSequence requirements.
  typedef boost::asio::const_buffer value_type;
  typedef const boost::asio::const_buffer* const_iterator;
  const boost::asio::const_buffer* begin() const { return &buffer_; }
  const boost::asio::const_buffer* end() const { return &buffer_ + 1; }

private:
  boost::shared_ptr<std::vector<char> > data_;
  boost::asio::const_buffer buffer_;
};

class session
  : public boost::enable_shared_from_this<session>
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
    using namespace std; // For time_t, time and ctime.
    time_t now = time(0);
    shared_const_buffer buffer(ctime(&now));
    boost::asio::async_write(socket_, buffer,
        boost::bind(&session::handle_write, shared_from_this()));
  }

  void handle_write()
  {
  }

private:
  // The socket used to communicate with the client.
  tcp::socket socket_;
};

typedef boost::shared_ptr<session> session_ptr;

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    session_ptr new_session(new session(io_service_));
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  void handle_accept(session_ptr new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start();
    }

    new_session.reset(new session(io_service_));
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

private:
  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: reference_counted <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    using namespace std; // For atoi.
    server s(io_service, atoi(argv[1]));

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

I’m a java programmer trying to understand how boost asio work, there are some points I need help with. My questions are:

  1. In these lines:

    const boost::asio::const_buffer* begin() const { return &buffer_; }
    const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
    

    this shared_const_buffer is use to async_write later, so I think it should implement some kind of buffer but I don’t see any inherit signature. So define begin() and end() are enough?

  2. And in these lines:

    shared_const_buffer buffer(ctime(&now));
    boost::asio::async_write(socket_, buffer, 
                             boost::bind(&session::handle_write, 
                                         shared_from_this()));    
    

    share_const_buffer has data_ is a shared pointer, but not itself, how is buffer valid until async_write actually writes the data?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T02:04:03+00:00Added an answer on May 30, 2026 at 2:04 am

    this shared_const_buffer is use to async_write() later, so I think it
    should implement some kind of buffer but I don’t see any inherit
    signature. So define begin() and end() are enough?

    The buffer used by the shared_const_buffer class is its _data member, a boost::shared_ptr<std::vector<char> >. Exposing iterators to the buffer is sufficient for using it with async_write().

    share_const_buffer has data_ is a shared pointer, but not itself, how
    is buffer valid until async_write() actually writes the data?

    The shared_const_buffer class implements the asio ConstBufferSequence type requirements

      // Implement the ConstBufferSequence requirements.
      typedef boost::asio::const_buffer value_type;
      typedef const boost::asio::const_buffer* const_iterator;
      const boost::asio::const_buffer* begin() const { return &buffer_; }
      const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
    

    so when invoking async_write it is copied, the documentation explicitly states this:

    buffers

    One or more buffers containing the data to be written.
    Although the buffers object may be copied as necessary, ownership of
    the underlying memory blocks is retained by the caller, which must
    guarantee that they remain valid until the handler is called.

    The underlying data however, is not copied since it is retained in a shared_ptr. You can see this can be seen by sprinkling some debugging statements

    --- reference_counted.cpp   2012-02-19 08:30:32.000000000 -0600
    +++ reference_counted_good.cpp  2012-02-19 08:26:27.000000000 -0600
    @@ -26,9 +26,7 @@
         : data_(new std::vector<char>(data.begin(), data.end())),
           buffer_(boost::asio::buffer(*data_))
       {
    -      std::cout << "shared_const_buffer()" << std::endl;
       }
    -  ~shared_const_buffer() { std::cout << "~shared_const_buffer() buffer use count: " << data_.use_count() << std::endl; }
    
       // Implement the ConstBufferSequence requirements.
       typedef boost::asio::const_buffer value_type;
    @@ -66,7 +64,6 @@
    
       void handle_write()
       {
    -      std::cout << "handle_write" << std::endl;
       }
    
     private:
    

    and running it

    Sam-Millers-MacBook-Pro:stackoverflow samm$ ./a.out 1234
    shared_const_buffer()
    ~shared_const_buffer() buffer use count: 8
    ~shared_const_buffer() buffer use count: 7
    ~shared_const_buffer() buffer use count: 6
    ~shared_const_buffer() buffer use count: 5
    ~shared_const_buffer() buffer use count: 4
    ~shared_const_buffer() buffer use count: 3
    ~shared_const_buffer() buffer use count: 3
    ~shared_const_buffer() buffer use count: 2
    handle_write
    ~shared_const_buffer() buffer use count: 2
    ~shared_const_buffer() buffer use count: 1
    

    in another shell

    Sam-Millers-MacBook-Pro:stackoverflow samm$ telnet localhost 1234
    Trying ::1...
    telnet: connect to address ::1: Connection refused
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    Sun Feb 19 08:22:56 2012
    Connection closed by foreign host.
    Sam-Millers-MacBook-Pro:stackoverflow samm$ 
    

    So the actual buffer remains valid until the last shared_const_buffer goes out of scope and runs the descriptor

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Sample code that shows how to create threads using MFC declares the thread function
Sample code using the app.config: ContextFactory contextFactory = ContextFactory.Instance; IServiceContext serviceContext = contextFactory.NewContext(); app.config
A sample application I was looking at has this in environment.rb : config.gem 'rails'
Sample code: using System; using System.IO; using System.Collections.Generic; using System.Text; using iTextSharp.text; using iTextSharp.text.pdf;
Sample in C# or VB.NET are welcome. I want to bind the following query
Sample data: !!Part|123456,ABCDEF,ABC132!! The comma delimited list can be any number of any combination
Sample Data: 603 Some garbage data not related to me, 55, 113 -> 1-ENST0000
Sample Text: SUBJECT = 'NETHERLANDS MUSIC EPA' CONTENT = 'Michael Buble performs in Amsterdam
Sample XML. <person> <name>Joe Dirt</name> <ssn>123-45-6789</ssn> <dob>07/04/1981</dob> </person> Sample Java Class public class Person(){
Sample code: public class Service1 { public int Service1() { .... } } public

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.