Smart Pointers
Fundamentals on Computing for Robotics, Graphics and Computer Vision

Prerequisites

In this laboratory, you are going to write several small programs covering the basic aspects of smart pointers. Please use the same compiler and setup that in previous laboratories. Please do not forget to use these CXXFLAGS when compiling with g++: -Wall -Wextra -pedantic -Werror. These flags would help you to write more solid code. Ideally, you should use cmake as your building tool. Also, you could consider adding the following lines to your CMakeLists.txt to ensure you are working on C++17.

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

The easiest approach to complete this lab is to compile with the provided CMake files. To follow this approach, please first clone the class’ repo.

cd <your root directory for FoC repo>
git clone git clone https://github.com/adolfomunoz/FoC.git
cd FoC

Once the clonation has finished, let’s continue building some test programs:

cd src/assignment_09_classes_materials
mkdir build-debug
cd build-debug
cmake -DCMAKE_BUILD_TYPE=Debug ../ # generate the Makefile with cmake
make -j4 # compile the examples in parallel with 4 jobs

Do not hesitate to contact the faculty in case of doubts about the exercises.

Identify memory leaks and remove them

Identify all the memory leaks in the file to_fix_memory_leaks.cpp and avoid them using smart pointers. This example only requires std::unique_ptr.

Please understand and run the original program before starting your solution.

#include <iostream>


struct point
{
  int x, y;
  bool not_zero() const { return x!=0 || y!=0; };
};

struct point_node
{
  point p;
  point_node* next;

  point_node(const point& other_p, point_node* other_next) : p(other_p), next(other_next) {}
};

point* copy_point(const point& p)
{
  point* point_ptr = new point(p);

  if (p.x > 1)
    return nullptr;

  return point_ptr;
}

int main()
{
  const size_t n = 4;
  point points[n]={ {0, 0}, {1, 1}, {0, 0}, {1, 1} };

  // save points whose coordinates are not (0, 0)
  point_node* list = nullptr;

  for(const auto& p: points) {
    point_node* node = new point_node(p, nullptr);
    if(p.not_zero()) {
      if(list == nullptr) {
        list = node;
      } else {
        point_node* iter=list;
        while(iter->next != nullptr) {
          iter = iter->next;
        }
        iter->next = node;
      }
    }
  }

  // print non-zero nodes
  for(point_node* iter = list; iter != nullptr; iter = iter->next) {
    std::cout << "(x, y): " << iter->p.x << ", " << iter->p.y << std::endl;
  }
}

Using shared pointers

Please describe what the following program does and answer the following questions:

  1. How many objects (variables) are allocated in the stack and in the heap?
  2. Can both sp1 and sp2 modify the object in the heap?
  3. Does the destruction of sp2 releases the memory allocated in the heap?
#include <iostream>
#include <memory>

int main() {

  auto sp1 = std::make_shared<int>(1);

  // please remember that the value returned by use_count should be considered
  // approximate in multithreading applications
  // https://en.cppreference.com/w/cpp/memory/shared_ptr/use_count.html
  // provides more information
  std::cout << "sp1.use_count(): " << sp1.use_count() << std::endl;

  { // new scope
    std::shared_ptr<int> sp2(sp1);
    std::cout << "sp1.use_count(): " << sp1.use_count() << std::endl;
    std::cout << "sp2.use_count(): " << sp2.use_count() << std::endl;
  }

  std::cout << "sp1.use_count(): " << sp1.use_count() << std::endl;
  std::cout << "Is sp1 unique? " << (sp1.use_count() == 1) << std::endl;
}

Writing simple code with smart pointers

Starting from the max_min_heap_2d_matrix.cpp code, replace all dynamic memory operations with smart pointers. The resulting file should be named max_min_sp_2d_matrix.cpp. The maximum and minimum values should be printed by reading the value from an smart pointer as well.

Submission

Please group the all the files within a zip. In those assignments with text questions, add then at the beginning of the file as C++ comments.

Before submitting, remember to talk to your teacher and have a small interview describing and answering questions about the job you have done and the decissions you have made. This interview is 20% of the total grade of the assignment, while the submitted material is evaluated for the other 80%.

All source code files, must include a comment on top with the names and NIAs of the students involved on their development. Then, all source code files, including directory structure, must be compressed into a single zip file with the following naming:

The compressed file must not contain anything else besides the source code files. Particularly, do not submit any binary file, neither executable, library nor object. The submission of the zip file must be done through the corresponding task in Moodle before the stablished deadline.