Previous Next

Learning Boost C++ Libraries Solve practical programming problems using powerful, portable, and expressive libraries from… (Arindam Mukherjee) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Arindam Mukherjee

移动

Solve practical programming problems using powerful, portable, and expressive libraries from Boost About This Book Learn to apply the breadth of Boost libraries, including containers, smart pointers, regular expressions, threads, network I/O, and other utilities through practical programming examples Write clear and succinct C++ code that is efficient and maintainable Speed up using the Boost libraries without any prior knowledge, using an in-depth tutorial introduction Who This Book Is For If you are a C++ programmer who has never used Boost libraries before, this book will get you up-to-speed with using them. Whether you are developing new C++ software or maintaining existing code written using Boost libraries, this hands-on introduction will help you decide on the right library and techniques to solve your practical programming problems. What You Will Learn Write efficient and maintainable code using expressive interfaces from Boost libraries Leverage a variety of flexible, practical, and highly efficient containers and algorithms beyond STL Solve common programming problems by applying a wide array of utility libraries Design and write portable multithreaded code that is easy to read and maintain Craft highly scalable and efficient TCP and UDP servers Build and deploy Boost libraries across a variety of popular platforms Use C++11 functionality and emulate C++11 language features in C++03 code In Detail Filled with dozens of working code examples that illustrate the use of over 40 popular Boost libraries, this book takes you on a tour of Boost, helping you to independently build the libraries from source and use them in your own code. The first half of the book focuses on basic programming interfaces including generic containers and algorithms, strings, resource management, exception safety, and a miscellany of programming utilities that make everyday programming chores easy. Following a short interlude that introduces template metaprogramming and functional

📄 File Format: PDF
💾 File Size: 2.9 MB
7
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Learning Boost C++ Libraries Solve practical programming problems using powerful, portable, and expressive libraries from Boost Arindam Mukherjee BIRMINGHAM - MUMBAI
📄 Page 3
Learning Boost C++ Libraries Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: July 2015 Production reference: 1280715 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78355-121-7 www.packtpub.com
📄 Page 4
Credits Author Arindam Mukherjee Reviewers Michael Medin Anthony Shoumikhin Drew Tennenbaum Sergey Zubkov Commissioning Editor Usha Iyer Acquisition Editor Nikhil Karkal Content Development Editors Natasha DSouza Sweny Sukumaran Technical Editors Pramod Kumavat Saurabh Malhotra Mitali Somaiya Copy Editor Rashmi Sawant Project Coordinator Vijay Kushlani Proofreaders Stephen Copestake Safis Editing Indexer Hemangini Bari Graphics Sheetal Aute Production Coordinator Komal Ramchandani Cover Work Komal Ramchandani
📄 Page 5
About the Author Arindam Mukherjee is a senior principal software engineer at Symantec, Pune, India, where he is involved in the research and development of business continuity solutions for enterprises. He has used C++ extensively for developing large-scale distributed systems. He was a speaker at Dr. Dobb's Journal India Conference 2014 and is the organizer of regular meets for the Pune C++ and Boost Meetup. He believes that writing books and articles, speaking for interest groups, and engaging with the programming community are the best ways to develop a critical understanding of technology. He is also an amateur musician, dabbles in food photography, and loves profound discussions with his 4-year-old daughter, especially about dinosaurs and their diets. I would like to express my sincerest gratitude to Sergey Zubkov for helping me refine the content of this book with his critical reviews and observations. Special thanks to Anthony Shoumikhin, Drew Tennenbaum, and Michael Medin for their thoughtful reviews and feedback. A special word of thanks to Nikhil Karkal, Natasha DSouza, Pramod Kumavat, and Sweny Sukumaran at Packt Publishing for their tremendous support and helping me manage all the missed deadlines. Last but not least, I thank my father for making me believe as a child that writing books could be fun, my mother for far more than words can ever express, my wife for believing in my dream, and my daughter for making it all worthwhile.
📄 Page 6
About the Reviewers Michael Medin is a senior developer and lead architect of the NSClient++ project. He is an avid C++ developer and has been developing open source software using C++ and the Boost library for longer than he cares to remember. As always, I would like to thank my beloved, Xiqun, for putting up with me when I spend countless hours working on NSClient++ and my two daughters for always bringing a smile to my face. Anthony Shoumikhin is yet another geek who loves hacking, cycling, swimming, and occasional work at Microsoft. He grew up in Ukraine and spent his early years in a city of rocket science and secret technologies—Dnipropetrovsk. These days, he works in Redmond, WA, on an upcoming release of Microsoft Office for Mac and iOS. In his spare time, he creates full-stack mobile apps and funny low-level system hacks on Mac OS X and Linux (mostly in his beloved C++ empowered with Boost). Drew Tennenbaum was introduced to programming at the age of 12. As a present, his parents gave him his first computer, a Commodore 64. A family friend purchased a book titled, Assembly Language for Kids: Commodore 64. Bored one night, he began reading the book and instantly found attraction in learning how to make a machine perform specific tasks. He quickly took to assembly language, which is now the foundation for much of what he works on today.
📄 Page 7
He attended the University of Arizona, where he received a BS degree in Computer Science and Math. Since graduating from university in 1997, he has worked on a vast array of technologies, ranging from video games to embedded devices. He spent many years working on massively multiplayer online video games. In 2011, he was a Technical Director at BioWare, helping launch Star Wars: The Old Republic. More recently, he managed the development of the Appstore for Amazon's line of hardware devices, including the Kindle and Fire TV. In early 2015, he founded Titan Labs. Titan Labs is a small boutique consulting firm based in sunny Southern California. In his spare time, he enjoys riding one of his many motorcycles and also holds an amateur motorcycle racing license. I want to thank my parents for giving me the room to explore my passions in life. Without their patience, I would not have been where I am today, and more importantly, I would not have been the person I've become. I would also like to thank Dawn, my partner in life who supports me in anything I do and puts up with those late night programming sessions. Finally, I would like to thank all of my family members, including my grandmother, brother, and sister. Sergey Zubkov is a former biochemistry researcher who became a C++ programmer. He is currently working at Morgan Stanley and spends his free time updating http://cppreference.com.
📄 Page 8
www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
📄 Page 9
(This page has no text content)
📄 Page 10
[ i ] Table of Contents Preface ix Chapter 1: Introducing Boost 1 How it all started 1 What is Boost? 2 Getting started with Boost libraries 3 Necessary software 3 Linux toolchain 4 Windows toolchain 4 Obtaining and building Boost libraries 5 Planning your Boost sandbox 5 Library naming conventions 5 Library name components 5 Library name layouts 6 Installing a Boost binary distribution 8 Building and installing the Boost libraries from source 10 Using Boost libraries in your projects 15 Linking against Boost libraries on Linux 16 Linking against Boost libraries on Windows 17 Building the code listings in this book 20 CMake 20 Code examples 20 Self-test questions 23 Summary 23 Chapter 2: The First Brush with Boost's Utilities 25 Simple data structures 25 Boost.Optional 26 Accessing values stored in boost::optional 28 get_value_or 29 Boost.Optional versus pointers 30
📄 Page 11
Table of Contents [ ii ] Boost.Tuple 30 Creating tuples 31 Accessing tuple elements 32 Comparing tuples 33 Writing generic code using tuples 34 Working with heterogeneous values 34 Boost.Variant 35 Accessing values in a variant 37 Defining recursive variants 41 Boost.Any 47 Boost.Conversion 50 lexical_cast 51 Handling command-line arguments 52 Designing command-line options 52 The diff command – a case study 53 Using Boost.Program_Options 55 Parsing positional parameters 58 Multiple option values 59 Other utilities and compile-time checks 60 BOOST_CURRENT_FUNCTION 61 Boost.Swap 63 Compile-time asserts 65 Diagnostics using preprocessor macros 69 Self-test questions 73 Summary 74 References 74 Chapter 3: Memory Management and Exception Safety 75 Dynamic memory allocation and exception safety 76 Exception safety and RAII 78 Smart pointers 80 Unique ownership semantics 81 boost::scoped_ptr 81 boost::scoped_array 90 std::unique_ptr 92 Shared ownership semantics 96 boost::shared_ptr and std::shared_ptr 96 Intrusive smart pointers – boost::intrusive_ptr 109 shared_array 113 Managing non-memory resources using smart pointers 114 Self-test questions 115 Summary 117 References 117
📄 Page 12
Table of Contents [ iii ] Chapter 4: Working with Strings 119 Text processing with Boost String Algorithms library 120 Using Boost String Algorithms 124 Find algorithms 126 Case-conversion and trimming algorithms 133 The replace and erase algorithms 136 The split and join algorithms 137 Splitting text using the Boost Tokenizer library 139 Tokenizing based on separators 140 Tokenizing records with fields containing metacharacters 142 Tokenizing records with fixed-length fields 144 Writing your own tokenizer functions 146 Regular expressions using Boost.Regex 152 Regular expression syntax 152 Atoms 152 Quantifiers 153 Character classes 154 Anchors 154 Sub-expressions 154 Disjunctions 155 Using Boost.Regex to parse regular expressions 155 Matching text 156 Searching text 157 Tokenizing text using regex 160 Replacing text 163 Self-test questions 164 Summary 165 Chapter 5: Effective Data Structures beyond STL 167 Boost Container library 168 Move-awareness and in-place construction 169 Nonstandard containers 172 Flat associative containers 172 slist 175 stable_vector 181 static_vector 184 Fast lookups using Boost Unordered containers 186 Containers for dynamically-allocated objects 190 Ownership semantics of pointer containers 197 Null pointers in pointer containers 202 Expressive initialization and assignment using Boost.Assign 203 Assigning lists of values to containers 203 Initializing containers with lists of values 206 Initializing pointer containers and assigning values 209
📄 Page 13
Table of Contents [ iv ] Iteration patterns using Boost.Iterator 212 Smart iteration using Boost.Iterator 212 Filter Iterator 213 Transform Iterator 215 Function Output Iterator 216 Creating conforming iterators for custom classes 218 Self-test questions 224 Summary 225 References 225 Chapter 6: Bimap and Multi-index Containers 227 Containers for multi-criteria lookups 228 Boost Multi-index containers 230 Index types 233 Range lookups using lambda 235 Insertions and updates 236 Boost Bimap 239 Collection types 242 More ways to use bimaps 245 Tagged access 245 Projections 246 Self-test questions 247 Summary 248 References 248 Chapter 7: Higher Order and Compile-time Programming 249 Higher order programming with Boost 250 Function objects 251 Lambdas – unnamed function literals 255 Delegates and closures 259 Partial function application 262 Compile-time programming with Boost 267 Basic compile-time control flow using templates 267 Branching 267 Recursion 269 Boost Type Traits 270 SFINAE and enable_if / disable_if 275 The Boost Metaprogramming Library (MPL) 278 Metafunctions 278 Using MPL metafunctions 278 Domain Specific Embedded Languages 284 Lazy evaluation 284 Expression templates 285
📄 Page 14
Table of Contents [ v ] Boost Phoenix 290 Boost Spirit Parser Framework 296 Using Spirit Qi 297 Self-test questions 308 Summary 309 References 309 Chapter 8: Date and Time Libraries 311 Date and time calculations with Boost Date Time 311 Dates from the Gregorian calendar 312 Creating date objects 312 Handling date durations 314 Date periods 314 Posix time 316 Constructing time points and durations 316 Resolution 318 Time periods 320 Time iterator 321 Using Chrono to measure time 322 Durations 322 Duration arithmetic 324 Clocks and time points 326 Measuring program performance using Boost Timer 329 cpu_timer 329 auto_cpu_timer 332 Self-test questions 333 Summary 334 References 334 Chapter 9: Files, Directories, and IOStreams 335 Managing files and directories with Boost Filesystem 336 Manipulating paths 336 Printing paths 336 Constructing paths 340 Breaking paths into components 342 Traversing directories 347 Querying filesystem entries 350 Performing operations on files 354 Creating directories 354 Creating symbolic links 355 Copying files 356 Moving and deleting files 358 Path-aware fstreams 358
📄 Page 15
Table of Contents [ vi ] Extensible I/O with Boost IOStreams 359 Architecture of Boost IOStreams 359 Using devices 361 Devices for file I/O 361 Devices for reading and writing to memory 363 Using filters 365 Basic filters 366 Filters for compression and decompression 368 Composing filters 370 Self-test questions 374 Summary 375 Chapter 10: Concurrency with Boost 377 Creating concurrent tasks with Boost Thread 378 Using Boost Threads 379 Moving threads and waiting on threads 382 Thread IDs 384 Cores and threads 386 Managing shared data 386 Creating and coordinating concurrent tasks 386 boost::future and boost::promise 388 Waiting for future 390 Throwing exceptions across threads 391 shared_future 393 std::future and std::promise 395 std::packaged_task and std::async 396 Lock-based thread synchronization methods 400 Data races and atomic operations 401 Mutual exclusion and critical sections 403 Synchronizing on conditions 412 The Readers-Writers problem 417 Standard Library primitives 423 Boost Coroutine 423 Asymmetric coroutines 424 Self-test questions 426 Summary 427 References 428 Chapter 11: Network Programming Using Boost Asio 429 Task execution with Asio 430 IO Service, queues, and handlers 430 Handler states – run_one, poll, and poll_one 432 post versus dispatch 432
📄 Page 16
Table of Contents [ vii ] Concurrent execution via thread pools 434 io_service::work 436 Serialized and ordered execution via strands 437 Network I/O using Asio 441 UDP and TCP 441 IP addresses 442 IPv4 addresses 442 IPv6 addresses 445 Endpoints, sockets, and name resolution 448 Ports 448 Sockets 448 Hostnames and domain names 449 Buffers 452 Buffer sequences for vectored I/O 453 Synchronous and asynchronous communications 455 Asio deadline timer 455 Asynchronous logic using Asio coroutines 458 UDP 461 Synchronous UDP client and server 461 Asynchronous UDP server 464 Performance and concurrency 470 TCP 474 Establishing a TCP connection 474 Synchronous TCP client and server 475 Asynchronous TCP server 480 Self-test questions 489 Summary 491 References 491 Appendix: C++11 Language Features Emulation 493 RAII 493 Copy semantics 495 The nothrow swap 498 Move semantics and rvalue references 499 rvalue references 501 rvalue-reference overloads 503 Move assignment 504 xvalues 505 Move emulation using Boost.Move 507 C++11 auto and Boost.Auto 511 Type deduction rules 512 Common uses 512 Boost.Auto 513
📄 Page 17
Table of Contents [ viii ] Range-based for-loops 513 Boost.Foreach 514 C++11 exception-handling improvements 515 Storing and rethrowing exceptions 515 Storing and rethrowing exception using Boost 517 Self-test questions 518 References 519 Index 521
📄 Page 18
[ ix ] Preface Boost is not just a collection of useful, portable, generic C++ libraries. It is an important incubator for ideas and concepts that make their way to the ISO C++ Standard itself. If you are involved in the development of software written in C++, then learning to use the Boost libraries would save you from reinventing the wheel, improve the quality of your software, and very likely push up your productivity. I first came across the Boost libraries a decade ago, while looking for a portable C++ regular expressions library. Over the next couple of days, porting Perl and Korn Shell text-processing code to C++ became a breeze, and I took an instant liking to Boost. In using many more Boost libraries to write software since then, I often found myself digging deep into the documentation, or asking questions on the mailing list and online forums to understand library semantics and nuances. As effective as that was, I always sorely missed a book that would get me started on the most useful Boost libraries and help me become productive faster. This is that book. Boost has a wide array of libraries for solving various kinds of programming tasks. This book is a tutorial introduction to a selection of over of the most useful libraries from Boost to solve programming problems effectively. The chosen libraries represent the breadth of cross-cutting concerns from software development, including data structures and algorithms, text processing, memory management, exception safety, date and time calculations, file and directory management, concurrency, and file and network I/O, among others. You will learn about each library by understanding the kind of problems it helps solve, learning the fundamental concepts associated with it, and looking at a series of code examples to understand how the library is used. Libraries introduced earlier in this book are freely used in later examples, exposing you to the frequent synergies that occur in practice between the Boost libraries.
📄 Page 19
Preface [ x ] As a collection of peer-reviewed, open source libraries, Boost draws heavily from community expertise. I firmly believe that this book will give you a strong practical foundation in using the Boost libraries. This foundation will reflect in the quality of the software you write, and also give you the leverage to engage with the Boost community and make valuable contributions to it. What this book covers Chapter 1, Introducing Boost, discusses how to set up a development environment to use the Boost libraries. We cover different ways of obtaining Boost library binary packages, building them from source for different configurations, and using them in a development environment. Chapter 2, The First Brush with Boost's Utilities, explores a handful of Boost libraries for common programming tasks that include dealing with variant data types, handling command-line arguments, and detecting the configuration parameters of the development environment. Chapter 3, Memory Management and Exception Safety, explains what is meant by exception safety, and shows how to write exception-safe code using the different smart pointer types provided by Boost and C++11. Chapter 4, Working with Strings, explores the Boost String Algorithms library for performing various computations with character strings, the Boost Range library for elegantly defining subsequences, the Boost Tokenizer library to split strings into tokens using different strategies, and the Boost Regex library to search for complex patterns in text. Chapter 5, Effective Data Structures beyond STL, deals with the Boost Container library focusing on containers not available in the C++ Standard Library. We see the Pointer Container library for storing dynamically-allocated objects in action, and use the Boost Iterator library to generate various value sequences from underlying containers. Chapter 6, Bimap and Multi-index Containers, looks at bidirectional maps and multi-index containers—two nifty container templates from Boost. Chapter 7, Higher Order and Compile-time Programming, delves into compile-time programming using Boost Type Traits and Template Metaprogramming libraries. We take a first look at Domain Specific Embedded Languages and use Boost Phoenix to build basic expression templates. We use Boost Spirit to build simple parsers using the Spirit Qi DSEL.
📄 Page 20
Preface [ xi ] Chapter 8, Date and Time Libraries, introduces the Boost Date Time and Boost Chrono libraries to represent dates, time points, intervals, and periods. Chapter 9, Files, Directories, and IOStreams, features the Boost Filesystem library for manipulating filesystem entries, and the Boost IOStreams library for performing type-safe I/O with rich semantics. Chapter 10, Concurrency with Boost, uses the Boost Thread library and Boost Coroutine library to write concurrent logic, and shows various synchronization techniques in action. Chapter 11, Network Programming Using Boost Asio, shows techniques for writing scalable TCP and UDP servers and clients using the Asio library. Appendix, C++11 Language Features Emulation, summarizes C++11 move semantics and Boost's emulation of several C++11 features in C++03. What you need for this book You will need a computer capable of running an operating system that supports a C++ compiler toolchain supported by Boost. You can find more details at http://www. boost.org/doc/libs/release/libs/log/doc/html/log/installation.html. To compile and run the code from this book, you will need to install the Boost libraries version 1.56 or later. See Chapter 1, Introducing Boost, for more details. Many code examples in this book require C++11 support, and thus, you should choose versions of your compiler that have good support for C++11. You can find more details at http://en.cppreference.com/w/cpp/compiler_support. A CMake project is provided with the downloadable source code to help you quickly build all the examples using your preferred build system (gmake or Microsoft Visual Studio). In order to use this, you need to install CMake version 2.8 or later. See Chapter 1, Introducing Boost, for more details. This book tries not to repeat content from the online reference manual. You should use the Boost library's online reference manuals liberally in conjunction with this book to discover additional properties, functions, and techniques. You can find the documentation at http://www.boost.org/doc/libs/. Finally, the code listings in this book are sometimes abridged for brevity and focus. The code examples accompanying this book are complete versions of these listings, and you should use them when trying to build the examples.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List