2
votes

Why should I use a custom handler allocator (custom_alloc_handler) of the examples in boost::asio: http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/example/allocation/server.cpp Here shown - how to do it, but do not explain why. And if it always gives some advantage, then why not use it in the other examples? Custom allocator is not in examples of: chat, web-server, etc. http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/examples.html#boost_asio.examples.buffers

1

1 Answers

3
votes

Asynchronous operations may need to allocate temporary objects. <...> All temporary objects associated with a handler will be deallocated before the upcall to the handler is performed. This allows the same memory to be reused for a subsequent asynchronous operation initiated by the handler.

In other words, the above technique is an optimization that allows the user to minimize the number of allocations/de-allocations, thus improving performance and reducing heap fragmentation.

And if it always gives some advantage, then why not use it in the other examples?

Every example emphasizes some specific piece of the Asio functionality. As for real life applications, premature optimizations are usually a bad idea, because they bring unnecessary complications. So, the above optimization, as well as any other one, should be used only where appropriate.