fbpx ...

Memory and resource management

This topic covers memory and resource management. It presents problems associated with resource management with modern C++ solutions like smart pointers. Optionally quick recap on exceptions can be made to align participants knowledge. Practical use of valgrind for memory problems is presented.

We will analyse such code

  struct FileWrapper {
    FileWrapper(std::string const& filePath)
            : m_file(fopen(filePath.c_str(), "rw")) {
        if(!m_file) {
            throw std::runtime_error("File not opened");
        }
    }

    ~FileWrapper() {
        fclose(m_file);
    }

    FileWrapper & operator<<(std::string const& text) {
        /* Not validation needed, invalid object cannot be created */
        fputs(text.c_str(), m_file);
        return *this;
    }

private:
    FILE* m_file;
};  
  #include <memory>
#include <map>
#include <string>

class Gadget {};
std::map<std::string, std::shared_ptr<Gadget>> gadgets;
// above wouldn't compile with C++03. Why?

void foo() {
    std::shared_ptr<Gadget> p1{new Gadget()};   // reference counter = 1
    {
        auto p2 = p1;                           // copy (reference counter == 2)
        gadgets.insert(make_pair("mp3", p2));   // copy (reference counter == 3)
        p2->use();
    }                                           // destruction of p2, reference counter = 2
}                                               // destruction of p1, reference counter = 1

int main() {
    foo();
    gadgets.clear();                            // reference counter = 0 - gadget is removed
}  

Your abilities after Memory and resource management training

Agenda

Activities

Duration

Form

Order Memory and resource management training

Related trainings

Move semantics

Move semantics is implemented in smart pointers. It may help to understand how this operation exactly works.

Modern C++

Smart pointers are an important part of C++11 library.
ninjaletter

Już uciekasz?

Zanim to zrobisz, zapisz się na Ninjaletter, aby wiedzieć, co piszczy w C++. 

Informujemy, iż w celu realizacji usług dostępnych w naszym serwisie, optymalizacji jej treści, dostosowania strony do Państwa indywidualnych potrzeb oraz wyświetlania, personalizacji i mierzenia skuteczności reklam w ramach zewnętrznych sieci reklamowych korzystamy z informacji zapisanych za pomocą plików cookies na urządzeniach końcowych użytkowników. Pliki cookies można kontrolować za pomocą ustawień swojej przeglądarki internetowej. Dalsze korzystanie z naszego serwisu, bez zmiany ustawień przeglądarki internetowej oznacza, iż użytkownik akceptuje stosowanie plików cookies. Więcej informacji zawartych jest w polityce prywatności serwisu.