How to Use Memory Management and Smart Pointers in C++

In this tutorial, we will explore memory management and smart pointers in C++. 

Prerequisites

Managing Memory with malloc 

Let’s explore memory management in C++ using malloc and free. Understanding manual memory management is crucial for robotics programming, especially in resource-constrained environments. 

Open a terminal window, and type this: 

cd ~/Documents/cpp_tutorial 
code . 

Create a new C++ file and name it memory_management_example.cpp

Type the following code into the editor:

#include <iostream>
#include <cstdlib>  // For malloc and free

int main() {
    int *ptr = (int*) malloc(sizeof(int));  // Allocating memory for an integer
    if (ptr == nullptr) {
        std::cout << "Memory allocation failed" << std::endl;
        return -1;  // Return an error if memory allocation failed
    }
    
    *ptr = 5;  // Assigning value to the allocated memory
    std::cout << "Value at pointer: " << *ptr << std::endl;

    free(ptr);  // Freeing the allocated memory
    ptr = nullptr;  // Setting pointer to nullptr after freeing memory

    return 0;
}

In this code snippet, we use malloc to allocate memory for an integer and check if the memory allocation was successful. We then assign a value to this memory, print it, and finally, free the memory using free to avoid memory leaks. 

Setting the pointer to nullptr after freeing is a good practice to prevent dangling pointers.

Run the code.

1-memory-management

You should see the output “Value at pointer: 5”, confirming that our memory management operations are functioning correctly.

Using Smart Pointers

Let’s explore smart pointers in C++, which provide automatic memory management and help prevent memory leaks. We’ll look at unique_ptr, shared_ptr, and weak_ptr, which are part of modern C++’s memory management toolkit. 

Create a new C++ file and name it smart_pointers.cpp

Type the following code into the editor:

#include <iostream>
#include <memory>

// Sensor class representing a sensor with a name and a value
class Sensor {
private:
    std::string name;
    double value;

public:
    Sensor(const std::string& name, double value) : name(name), value(value) {}

    void printInfo() const {
        std::cout << "Sensor: " << name << ", Value: " << value << std::endl;
    }
};

int main() {
    // Create a unique_ptr to a Sensor object
    std::unique_ptr<Sensor> sensor1 = std::make_unique<Sensor>("TemperatureSensor", 25.5);
    sensor1->printInfo();

    // Create a shared_ptr to a Sensor object
    std::shared_ptr<Sensor> sensor2 = std::make_shared<Sensor>("HumiditySensor", 60.0);
    sensor2->printInfo();

    // Create a weak_ptr to the shared_ptr
    std::weak_ptr<Sensor> weak_sensor = sensor2;
    if (auto shared_sensor = weak_sensor.lock()) {
        shared_sensor->printInfo();
    }

    return 0;
}

In this code, we define a Sensor class that represents a sensor with a name and a value.

In the main() function, we demonstrate the usage of different smart pointers:

  • unique_ptr: We create a unique_ptr to a Sensor object using std::make_unique(). The unique_ptr ensures exclusive ownership and automatically deletes the object when it goes out of scope.
  • shared_ptr: We create a shared_ptr to a Sensor object using std::make_shared(). The shared_ptr allows multiple pointers to share ownership of the object. The object is deleted when all shared_ptr instances go out of scope.
  • weak_ptr: We create a weak_ptr to the shared_ptr. The weak_ptr does not participate in ownership but can be used to check if the object is still valid. We use lock() to obtain a shared_ptr from the weak_ptr and access the object.

Run the code.

2-smart-pointers

The output displays the information of the Sensor objects created using smart pointers.

This example demonstrates how to use smart pointers in C++ for robotics projects. Smart pointers provide automatic memory management, helping to prevent memory leaks and simplify memory ownership. They are particularly useful when dealing with dynamically allocated objects and help make the code more robust and maintainable.

Thanks, and I’ll see you in the next tutorial.

Keep building!

How to Use Templates and Macros in C++

In this tutorial, we will explore templates and macros in C++.

Prerequisites

Employing Macros

Let’s explore how to use macros in C++ and their application in robotics projects. Macros are preprocessor directives that allow you to define reusable pieces of code, processed before compilation. 

Open a terminal window, and type this: 

cd ~/Documents/cpp_tutorial && code . 

Create a new C++ file and name it basic_macro.cpp.

Type the following code into the editor:

#include <iostream>

// Define a constant macro
#define PI 3.14159

// Define a function-like macro
#define AREA_CIRCLE(radius) (PI * (radius) * (radius))

int main() {
    double radius = 5.0;
    double area = AREA_CIRCLE(radius);

    std::cout << "The area of a circle with radius " << radius << " is: " << area << std::endl;

    return 0;
}

In this code, we define two macros:

  1. PI is a constant macro that defines the value of pi.
  2. AREA_CIRCLE(radius) is a function-like macro that calculates the area of a circle given its radius.

In the main() function, we use the AREA_CIRCLE macro to calculate the area of a circle with a radius of 5.0 and store the result in the area variable. We then print the calculated area using std::cout.

Run the code.

1-basic-macro

The output displays the calculated area of the circle using the AREA_CIRCLE macro.

It’s important to note that macros should be used sparingly and with caution, as they can sometimes lead to unexpected behavior if not used carefully. In modern C++, const variables, inline functions, or templates are often preferred over macros when possible.

Implementing Template Functions

Let’s explore template functions in C++, which allow us to write generic functions that can work with different data types. This is particularly useful in robotics when dealing with various sensor data types or mathematical operations. 

Create a new C++ file and name it template_functions_example.cpp

Type the following code into the editor:

#include <iostream>

template<typename T>
T find_max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << "Max of 10 and 20 is: " << find_max<int>(10, 20) << std::endl;
    std::cout << "Max of 5.5 and 2.1 is: " << find_max<double>(5.5, 2.1) << std::endl;
    return 0;
}

In this code, we define a template function find_max that takes two parameters of the same type and returns the greater of the two. The function uses the ternary operator to compare the two values. We then test this function with integers and doubles to show its versatility.

Run the code.

2-template-functions-example

The output should display “Max of 10 and 20 is: 20” and “Max of 5.5 and 2.1 is: 5.5”, demonstrating how the template function adapts to different data types.

Defining Template Classes

Let’s explore template classes in C++, which allow us to create generic classes that can work with different data types. This is particularly useful for creating reusable data structures in robotics applications. 

Create a new C++ file and name it template_class.cpp.

Type the following code into the editor:

#include <iostream>

// Template class for a point in 2D space
template <typename T>
class Point {
private:
    T x;
    T y;

public:
    Point(T x, T y) : x(x), y(y) {}

    T getX() const { return x; }
    T getY() const { return y; }

    void printPoint() const {
        std::cout << "(" << x << ", " << y << ")" << std::endl;
    }
};

int main() {
    Point<int> int_point(5, 10);
    Point<double> double_point(3.14, 2.71);

    std::cout << "Integer point: ";
    int_point.printPoint();

    std::cout << "Double point: ";
    double_point.printPoint();

    return 0;
}

In this code, we define a template class called Point that represents a point in 2D space. The class has two private member variables, x and y, of type T. The typename keyword is used to specify that T is a type parameter.

The Point class has a constructor that takes x and y values and initializes the member variables. It also provides getter functions getX() and getY() to access the values of x and y, respectively. The printPoint() function is a member function that prints the point in the format (x, y).

In the main() function, we create two instances of the Point class: int_point with integer values and double_point with double values. 

We use the printPoint() function to print the points and verify that the template class works correctly with different data types.

Run the code.

3-template-class

The output displays the points created with integer and double values.

Template classes provide flexibility and help reduce code duplication, making the code more maintainable and efficient.

Thanks, and I’ll see you in the next tutorial.

Keep building!

How to Use Lambda Expressions and File I/O in C++

In this tutorial, we will explore lambda expressions and file I/O using C++.

Prerequisites

Using Lambda Expressions 

Let’s explore lambda expressions in C++ and how they can be used in robotics projects. 

Lambda expressions allow us to define anonymous functions inline, which is particularly useful for operations like sorting sensor data or defining quick callback functions. 

Open a terminal window, and type this:

cd ~/Documents/cpp_tutorial
code .

Create a new C++ file and name it lambda_sensors.cpp

Type the following code into the editor:

#include <iostream>
#include <vector>
#include <algorithm>  // Include for std::sort

int main() {
    // Example list of sensor readings (could be temperatures, distances, etc.)
    std::vector<int> sensorReadings = {90, 85, 60, 75, 100};

    // Print original readings
    std::cout << "Original readings: ";
    for (int reading : sensorReadings) {
        std::cout << reading << " ";
    }
    std::cout << std::endl;

    // Using a lambda expression to sort the readings in descending order
    std::sort(sensorReadings.begin(), sensorReadings.end(), [](int a, int b) {
        return a > b;  // Comparison criterion defined inline
    });

    // Print sorted readings
    std::cout << "Sorted readings (desc): ";
    for (int reading : sensorReadings) {
        std::cout << reading << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this code, we start with a vector of integers representing sensor readings. The lambda expression is used within the std::sort function. Here, the lambda (int a, int b) { return a > b; } defines an inline function that tells std::sort how to compare two elements, specifying that we want to sort in descending order without the need for a separate function.

Run the code.

1-lambda-sensors

You should see the original and sorted readings displayed, showcasing how lambda expressions facilitate custom sorting in a concise manner.

This example highlights the utility of lambda expressions in C++, allowing for immediate definition of small scope functions directly within the code where they are needed. 

Iterating with for_each Loop

Let’s explore how to use the for_each loop in C++. The for_each loop is part of the C++ Standard Library and provides a clear, concise way to perform operations on every element in a range, such as an array or a container like a vector. This is particularly useful in robotics for tasks like processing sensor data, where you need to apply the same operation to a series of values.

Let’s demonstrate the use of the for_each loop with an example where we’ll process a list of distances recorded by a robot’s sensors.

Create a new C++ file and name it for_each_loop.cpp.

Type the following code into the editor:

#include <iostream>
#include <vector>
#include <algorithm>  // Include for std::for_each

int main() {
    // Example list of distances measured by sensors (in meters)
    std::vector<int> distances = {5, 10, 3, 7, 9};

    // Print original distances
    std::cout << "Original distances: ";
    for (int distance : distances) {
        std::cout << distance << " ";
    }
    std::cout << std::endl;

    // Using a lambda expression with std::for_each to increment each distance by 1
    std::for_each(distances.begin(), distances.end(), [](int &d) {
        d += 1;  // Increment each element by 1
    });

    // Print updated distances
    std::cout << "Updated distances: ";
    for (int distance : distances) {
        std::cout << distance << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this example, we begin with a vector of integers representing distances recorded by a robot. We use std::for_each along with a lambda expression that increments each element in the vector. The lambda (int &d) { d += 1; } directly modifies each element by adding 1, demonstrating an efficient way to process and update data in-place.

Run the code.

2-for-each-loop

You should see both the original and updated distances displayed, showing the practical application of the for_each loop in modifying elements directly.

Handling File Input and output

Let’s explore how to handle file input and output in C++ and its applications in robotics projects.

File input and output are essential operations in many programs, including robotics applications. In C++, the <fstream> library provides classes for reading from and writing to files. The ifstream class is used for reading from files, while the ofstream class is used for writing to files.

Let’s create a new C++ file named file_io_example.cpp to demonstrate file input and output.

Type the following code into the editor:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::string filename = "robot_data.txt";
    std::ofstream output_file(filename);

    if (output_file.is_open()) {
        output_file << "Sensor1: 10.5\n";
        output_file << "Sensor2: 20.7\n";
        output_file << "Sensor3: 15.2\n";
        output_file.close();
        std::cout << "Data written to file: " << filename << std::endl;
    } else {
        std::cout << "Unable to open file for writing." << std::endl;
    }

    std::ifstream input_file(filename);
    std::string line;

    if (input_file.is_open()) {
        while (std::getline(input_file, line)) {
            std::cout << line << std::endl;
        }
        input_file.close();
    } else {
        std::cout << "Unable to open file for reading." << std::endl;
    }

    return 0;
}

In this code, we first create a file named “robot_data.txt” using an ofstream object. We check if the file is successfully opened using the is_open() function. If the file is open, we write some sensor data to the file using the << operator and then close the file.

Next, we read the data from the same file using an ifstream object. We check if the file is successfully opened for reading. If the file is open, we read the file line by line using getline() and print each line to the console. After reading, we close the file.

Run the code.

3-file-io-example

The output confirms that the data was written to the file and then displays the contents of the file.

In robotics projects, file I/O can be used for various purposes, such as saving sensor data, reading configuration files, or storing robot states for analysis or debugging.

Thanks, and I’ll see you in the next tutorial.

Keep building!