Home


Lesson 10

Smart pointers

Task 0

Create own class. Write a destructor shows a text in the console.

In main method create a new object of the class (use "new" keyword").

Do you see destructor's output?

Task 1

Change main method, program will start deallocating memory without "delete" keyword.


unique_ptr<A> smart_a(new A(20)); // We use new, but we're wrapping poitner in unique_ptr
cout << smart_a->i << endl; // we can use smart_a like a poitner
    

Types of smart poitners

  • unique_ptr - deleting poitner deletes an object
  • shared_ptr - we share having an object; last deleted shared_ptr deletes reffered object
  • weak_ptr - works like shared_ptr, but it doesn't extend object's lifespan

Task 2

Create a structure of linked list. Create a list with 4 elements. Use smart poitners to manage memory.

Task 3

Implement class diagram:

Class diagram

Simple smart diagram for a few entities

Additional rules

  1. World is not sharing a country.
  2. Country can exist without any company.
  3. If we delete a country, we should delete its companies as well.
  4. Deleting a world deletes all counties and companies.