Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying C++ System Programming Cookbook
  • Table Of Contents Toc
C++ System Programming Cookbook

C++ System Programming Cookbook

By : Onorato Vaticone
3.8 (4)
close
close
C++ System Programming Cookbook

C++ System Programming Cookbook

3.8 (4)
By: Onorato Vaticone

Overview of this book

C++ is the preferred language for system programming due to its efficient low-level computation, data abstraction, and object-oriented features. System programming is about designing and writing computer programs that interact closely with the underlying operating system and allow computer hardware to interface with the programmer and the user. The C++ System Programming Cookbook will serve as a reference for developers who want to have ready-to-use solutions for the essential aspects of system programming using the latest C++ standards wherever possible. This C++ book starts out by giving you an overview of system programming and refreshing your C++ knowledge. Moving ahead, you will learn how to deal with threads and processes, before going on to discover recipes for how to manage memory. The concluding chapters will then help you understand how processes communicate and how to interact with the console (console I/O). Finally, you will learn how to deal with time interfaces, signals, and CPU scheduling. By the end of the book, you will become adept at developing robust systems applications using C++.
Table of Contents (13 chapters)
close
close

Smart pointers – unique_ptr and shared_ptr

This recipe will show the basic usage of unique_ptr and shared_ptr. These smart pointers are the main helpers for programmers who don't want to deal with memory deallocation manually. Once you've learned how to use them properly, this will save headaches and nights of debugging sessions.

How to do it...

In this section, we'll look at the basic use of two smart pointers, std::unique_ptr and std::shared_ptr:

  1. Let's develop a unique_ptr example by developing the following class:
#include <iostream>
#include <memory>
class CruiseControl
{
public:
CruiseControl()
{
std::cout << "CruiseControl object created" << std::endl;
};
~CruiseControl()
{
std::cout << "CruiseControl object destroyed" << std::endl;
}
void increaseSpeedTo(int speed)
{
std::cout << "Speed at " << speed << std::endl;
};
};
  1. Now, let's develop a main class by calling the preceding class:
int main ()
{
std::cout << "unique_ptr test started" << std::endl;
std::unique_ptr<CruiseControl> cruiseControl =
std::make_unique<CruiseControl>();
cruiseControl->increaseSpeedTo(12);
std::cout << "unique_ptr test finished" << std::endl;
}
  1. Let's compile g++ unique_ptr_01.cpp.
  2. Another example with unique_ptr shows its behavior with arrays. Let's reuse the same class (CruiseControl):
int main ()
{
std::cout << "unique_ptr test started" << std::endl;
std::unique_ptr<CruiseControl[]> cruiseControl =
std::make_unique<CruiseControl[]>(3);
cruiseControl[1].increaseSpeedTo(12);
std::cout << "unique_ptr test finished" << std::endl;
}
  1. Let's see std::shared_ptr in action with a small program:
#include <iostream>
#include <memory>
class CruiseControl
{
public:
CruiseControl()
{
std::cout << "CruiseControl object created" << std::endl;
};
~CruiseControl()
{
std::cout << "CruiseControl object destroyed" << std::endl;
}
void increaseSpeedTo(int speed)
{
std::cout << "Speed at " << speed << std::endl;
};
};

main looks like this:

int main ()
{
std::cout << "shared_ptr test started" << std::endl;
std::shared_ptr<CruiseControl> cruiseControlMaster(nullptr);
{
std::shared_ptr<CruiseControl> cruiseControlSlave =
std::make_shared<CruiseControl>();
cruiseControlMaster = cruiseControlSlave;
}
std::cout << "shared_ptr test finished" << std::endl;
}

The How it works... section will describe these three programs in detail.

How it works...

By running the first unique_ptr program, that is, ./a.out, we get the following output:

unique_ptr is a smart pointer that embodies the concept of unique ownership. Unique ownership, simply put, means that there is one and only one variable that can own a pointer. The first consequence of this concept is that the copy operator is not allowed on two unique pointer variables. Just move is allowed, where the ownership is transferred from one variable to another. The executable that was run shows that the object is deallocated at the end of the current scope (in this case, the main function): CruiseControl object destroyed. The fact that the developer doesn't need to bother remembering to call delete when needed, but still keep control over memory, is one of the main advantages of C++ over garbage collector-based languages.

In the second unique_ptr example, with arrays, there are three objects of the CruiseControl type that have been allocated and then released. For this, the output is as follows:

    The third example shows usage of shared_ptr. The output of the program is as follows:

    The shared_ptr smart pointer represents the concept that an object is being pointed at (that is, by the owner) by more than one variable. In this case, we're talking about shared ownership. It is clear that the rules are different from the unique_ptr case. An object cannot be released until at least one variable is using it. In this example, we defined a cruiseControlMaster variable pointing to nullptr. Then, we defined a block and in that block, we defined another variable: cruiseControlSlave. So far, so good! Then, still inside the block, we assigned the cruiseControlSlave pointer to cruiseControlMaster. At this point, the object allocated has two pointers: cruiseControlMaster and cruiseControlSlave. When this block is closed, the cruiseControlSlave destructor is called but the object is not freed as it is still used by another one: cruiseControlMaster! When the program finishes, we see the shared_ptr test finished log and immediately after the cruiseControlMaster, as it is the only one pointing to the CruiseControl object release, the object and then the constructor is called, as reported in the CruiseControl object destroyed log.

    Clearly, the shared_ptr data type has a concept of reference counting to keep track of the number of pointers. These references are increased during the constructors (not always; the move constructor isn't) and the copy assignment operator and decreased in the destructors.

    Can the reference counting variable be safely increased and decreased? The pointers to the same object might be in different threads, so manipulating this variable might be an issue. This is not an issue as the reference counting variable is atomically managed (that is, it is an atomic variable).

    One last point about the size. unique_ptr is as big as a raw pointer, whereas shared_ptr is typically double the size of unique_ptr because of the reference counting variable.

    There's more...

    See also

    The books Effective Modern C++ by Scott Meyers and The C++ Programming Language by Bjarne Stroustrup cover these topics in great detail.

    CONTINUE READING
    83
    Tech Concepts
    36
    Programming languages
    73
    Tech Tools
    Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
    Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
    Icon 50+ new titles added per month and exclusive early access to books as they are being written.
    C++ System Programming Cookbook
    notes
    bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

    Change the font size

    margin-width Margin width

    Change margin width

    day-mode Day/Sepia/Night Modes

    Change background colour

    Close icon Search
    Country selected

    Close icon Your notes and bookmarks

    Confirmation

    Modal Close icon
    claim successful

    Buy this book with your credits?

    Modal Close icon
    Are you sure you want to buy this book with one of your credits?
    Close
    YES, BUY

    Submit Your Feedback

    Modal Close icon
    Modal Close icon
    Modal Close icon