Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Boost C++ Application Development  Cookbook
Boost C++ Application Development  Cookbook

Boost C++ Application Development Cookbook: Recipes to simplify your application development , Second Edition

Arrow left icon
Profile Icon Anton Polukhin Alekseevic Profile Icon Anton Polukhin Alekseevic
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (5 Ratings)
Paperback Aug 2017 438 pages 2nd Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Anton Polukhin Alekseevic Profile Icon Anton Polukhin Alekseevic
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (5 Ratings)
Paperback Aug 2017 438 pages 2nd Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Boost C++ Application Development Cookbook

Managing Resources

In this chapter, we will cover the following topics:

  • Managing local pointers to classes that do not leave scope
  • Reference counting of pointers to classes used across functions
  • Managing local pointers to arrays that do not leave scope
  • Reference counting of pointers to arrays used across functions
  • Storing any functional objects in a variable
  • Passing function pointer in a variable
  • Passing C++11 lambda functions in a variable
  • Containers of pointers
  • Do it at scope exit!
  • Initializing the base class by the member of the derived class

Introduction

In this chapter, we'll continue to deal with datatypes, introduced by the Boost libraries, mostly focusing on working with the pointers. We'll see how to easily manage resources, how to use a datatype capable of storing any functional objects, functions, and lambda expressions. After reading this chapter, your code will become more reliable and memory leaks will become history.

Managing local pointers to classes that do not leave scope

Sometimes, we are required to dynamically allocate memory and construct a class in that memory. That's where the troubles start. Take a look at the following code:

bool foo1() { 
foo_class* p = new foo_class("Some data");

const bool something_else_happened = some_function1(*p);
if (something_else_happened) {
delete p;
return false;
}

some_function2(p);

delete p;
return true;
}

This code looks correct at first glance. But, what if some_function1() or some_function2() throws an exception? In that case, p won't be deleted. Let's fix it in the following way:

bool foo2() { 
foo_class* p = new foo_class("Some data");
try {
const bool something_else_happened = some_function1(*p);
if (something_else_happened) {
delete...

Reference counting of pointers to classes used across functions

Imagine that you have some dynamically allocated structure containing data, and you want to process it in different threads of execution. The code to do this is as follows:

#include <boost/thread.hpp> 
#include <boost/bind.hpp>

void process1(const foo_class* p);
void process2(const foo_class* p);
void process3(const foo_class* p);

void foo1() {
while (foo_class* p = get_data()) // C way
{
// There will be too many threads soon, see
// recipe 'Parallel execution of different tasks'
// for a good way to avoid uncontrolled growth of threads
boost::thread(boost::bind(&process1, p))
.detach();
boost::thread(boost::bind(&process2, p))
.detach();
boost::thread(boost::bind(&process3, p))
.detach(...

Managing pointers to arrays that do not leave scope

We already saw how to manage pointers to a resource in the Managing pointers to classes that do not leave scope recipe. But, when we deal with arrays, we need to call delete[] instead of a simple delete. Otherwise, there will be a memory leak. Take a look at the following code:

void may_throw1(char ch); 
void may_throw2(const char* buffer);

void foo() {
// we cannot allocate 10MB of memory on stack,
// so we allocate it on heap
char* buffer = new char[1024 * 1024 * 10];

// Oops. Here comes some code, that may throw.
// It was a bad idea to use raw pointer as the memory may leak!!
may_throw1(buffer[0]);
may_throw2(buffer);

delete[] buffer;
}

Getting ready

...

Reference counting of pointers to arrays used across functions

We continue coping with pointers, and our next task is to reference count an array. Let's take a look at the program that gets some data from the stream and processes it in different threads. The code to do this is as follows:

#include <cstring> 
#include <boost/thread.hpp>
#include <boost/bind.hpp>

void do_process(const char* data, std::size_t size);

void do_process_in_background(const char* data, std::size_t size) {
// We need to copy data, because we do not know,
// when it will be deallocated by the caller.
char* data_cpy = new char[size];
std::memcpy(data_cpy, data, size);

// Starting thread of execution to process data.
boost::thread(boost::bind(&do_process, data_cpy, size))
.detach();
boost::thread(boost::bind(&do_process, data_cpy, size...

Storing any functional objects in a variable

Consider the situation when you are developing a library that has its API declared in the header files and implementation in the source files. This library shall have a function that accepts any functional objects. Take a look at the following code:

// making a typedef for function pointer accepting int 
// and returning nothing
typedef void (*func_t)(int);

// Function that accepts pointer to function and
// calls accepted function for each integer that it has.
// It cannot work with functional objects :(
void process_integers(func_t f);

// Functional object
class int_processor {
const int min_;
const int max_;
bool& triggered_;

public:
int_processor(int min, int max, bool& triggered)
: min_(min)
, max_(max)
, triggered_(triggered)
{}

void operator()(int i) const {
if (i...

Passing function pointer in a variable

We are continuing with the previous example, and now we want to pass a pointer to a function in our process_integers() method. Shall we add an overload for just function pointers, or is there a more elegant way?

Getting ready

This recipe is continuing the previous one. You must read the previous recipe first.

How to do it...

Nothing needs to be done as boost::function<> is also constructible from the function pointers:

void my_ints_function(int i); 

int main() {
process_integers(&my_ints_function);
}
...

Passing C++11 lambda functions in a variable

We are continuing with the previous example, and now we want to use a lambda function with our process_integers() method.

Getting ready

This recipe is continuing the series of the previous two. You must read them first. You will also need a C++11 compatible compiler or at least a compiler with C++11 lambda support.

How to do it...

Nothing needs to be done as boost::function<> is also usable with lambda functions of any difficulty:

#include <deque>
//#include "your_project/process_integers.h"

void sample(...

Containers of pointers

There are such cases when we need to store pointers in the container. The examples are: storing polymorphic data in containers, forcing fast copy of data in containers, and strict exception requirements for operations with data in containers. In such cases, C++ programmer has the following choices:

  • Store pointers in containers and take care of their destructions using delete:
#include <set>
#include <algorithm>
#include <cassert>

template <class T>
struct ptr_cmp {
template <class T1>
bool operator()(const T1& v1, const T1& v2) const {
return operator ()(*v1, *v2);
}

bool operator()(const T& v1, const T& v2) const {
return std::less<T>()(v1, v2);
}
};

void example1() {
std::set<int*, ptr_cmp<int> > s;
s.insert(new int(1));
s.insert(new int(0));

// ...
...

Do it at scope exit!

If you were dealing with languages, such as Java, C#, or Delphi, you obviously were using the try {} finally{} construction. Let me briefly describe to you what do these language constructions do.

When a program leaves the current scope via return or exception, code in the finally block is executed. This mechanism is used as a replacement for the RAII pattern:

// Some pseudo code (suspiciously similar to Java code) 
try {
FileWriter f = new FileWriter("example_file.txt");
// Some code that may throw or return
// ...
} finally {
// Whatever happened in scope, this code will be executed
// and file will be correctly closed
if (f != null) {
f.close()
}
}

Is there a way to do such a thing in C++?

Getting ready

...

Initializing the base class by the member of the derived class

Let's take a look at the following example. We have some base class that has virtual functions and must be initialized with reference to the std::ostream object:

#include <boost/noncopyable.hpp> 
#include <sstream>

class tasks_processor: boost::noncopyable {
std::ostream& log_;

protected:
virtual void do_process() = 0;

public:
explicit tasks_processor(std::ostream& log)
: log_(log)
{}

void process() {
log_ << "Starting data processing";
do_process();
}
};

We also have a derived class that has a std::ostream object and implements the do_process() function:

class fake_tasks_processor: public tasks_processor { 
std::ostringstream logger_;

virtual void do_process() {
logger_ << "Fake processor processed...
Left arrow icon Right arrow icon

Key benefits

  • • Learn to use the Boost libraries to simplify your application development
  • • Learn to develop high quality, fast and portable applications
  • • Learn the relations between Boost and C++11/C++4/C++17

Description

If you want to take advantage of the real power of Boost and C++ and avoid the confusion about which library to use in which situation, then this book is for you. Beginning with the basics of Boost C++, you will move on to learn how the Boost libraries simplify application development. You will learn to convert data such as string to numbers, numbers to string, numbers to numbers and more. Managing resources will become a piece of cake. You’ll see what kind of work can be done at compile time and what Boost containers can do. You will learn everything for the development of high quality fast and portable applications. Write a program once and then you can use it on Linux, Windows, MacOS, Android operating systems. From manipulating images to graphs, directories, timers, files, networking – everyone will find an interesting topic. Be sure that knowledge from this book won’t get outdated, as more and more Boost libraries become part of the C++ Standard.

Who is this book for?

This book is for developers looking to improve their knowledge of Boost and who would like to simplify their application development processes. Prior C++ knowledge and basic knowledge of the standard library is assumed.

What you will learn

  • • Get familiar with new data types for everyday use
  • • Use smart pointers to manage resources
  • • Get to grips with compile-time computations and assertions
  • • Use Boost libraries for multithreading
  • • Learn about parallel execution of different task
  • • Perform common string-related tasks using Boost libraries
  • • Split all the processes, computations, and interactions to tasks and process them independently
  • • Learn the basics of working with graphs, stacktracing, testing and interprocess communications
  • • Explore different helper macros used to detect compiler, platform and Boost features

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 30, 2017
Length: 438 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787282247
Vendor :
Microsoft
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 30, 2017
Length: 438 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787282247
Vendor :
Microsoft
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
C++17 STL Cookbook
€41.99
Boost C++ Application Development  Cookbook
€41.99
Mastering the C++17 STL
€36.99
Total 120.97 Stars icon

Table of Contents

12 Chapters
Starting to Write Your Application Chevron down icon Chevron up icon
Managing Resources Chevron down icon Chevron up icon
Converting and Casting Chevron down icon Chevron up icon
Compile-Time Tricks Chevron down icon Chevron up icon
Multithreading Chevron down icon Chevron up icon
Manipulating Tasks Chevron down icon Chevron up icon
Manipulating Strings Chevron down icon Chevron up icon
Metaprogramming Chevron down icon Chevron up icon
Containers Chevron down icon Chevron up icon
Gathering Platform and Compiler Information Chevron down icon Chevron up icon
Working with the System Chevron down icon Chevron up icon
Scratching the Tip of the Iceberg Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(5 Ratings)
5 star 80%
4 star 0%
3 star 0%
2 star 0%
1 star 20%
Grigory Nov 03, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'm an experienced C++ programmer. One of my friends recommended this book and I enjoyed it.I use Boost for my own projects and know it pretty well. So I read the first few recipes fully and then just started reading Intro+HowToDoIt+TheresMore sections, skipping the detailed recipe description ("How It works").That was great. A lot of good tricks and modern C++ knowledge even for an experienced programmer!I strictly recommend reading this book.
Amazon Verified review Amazon
Jerome Lanteri Aug 30, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
good book for have reference and examples of use for boost C++ lib
Amazon Verified review Amazon
Sergey Platonov Oct 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Liked the easter eggs! Now seriously, the book is well written with a lot of practical advice. It is a set of recipes for everyday use, actually. Every topic (or recipe) consists of five parts: a short introduction of what this topic is about and what you'll need to use it, the recipe itself, explanation, additional information on the subject and related links. I've really enjoyed "There's more..." section. since usually it contains some interesting facts.Strongly recommend this book to every C++ developer, especially, if you just discovered boost or about to use boost ln your project.Of course, some topics seem to be pretty obvious, but I guess one can't know everything, so someone might find this helpful.
Amazon Verified review Amazon
Robert Toby Chaloner Jan 07, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a starting point for C++ Boost its very good. Gives a good grounding to build on
Amazon Verified review Amazon
Masum Serazi Feb 06, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This book is waste of money. Please don't buy it, rather go to boost official site and read their tutorial.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.