Skip to content

Latest commit

 

History

History
70 lines (51 loc) · 2.3 KB

Note.md

File metadata and controls

70 lines (51 loc) · 2.3 KB

Morden Cpp

Links

Misc

Smart Pointers

All programming languages must answer:

  • how to allocate the resources?
  • how to get the read only access to the resource?
  • how to get the mut/write access to the resource?
  • how to pass or move the access of the resource?
  • when to give up the access to the resource?
  • when to release the resources?
  • ~~
  • practical answer: resource ownership with lifetime

Back to Basics: Smart Pointers and RAII - Inbal Levi - CppCon 2021 hacking cpp: unique_ownership

  • The ownership model in C++
  • syntax and design of smart pointers and RAII

ownership events:

  • moving an object
  • passing an object as a function parameter
  • returning an object from a function

smart pointers

  • unique_ptr: single ownership
  • shared_ptr: multiple ownership
  • weak_ptr: non ownership

RESOURCE MANAGEMENT-RAII

  • Standard library classes using RAll
    • std:string, std::vector - free memory on DTOR
    • std::jthread - rejoin on DTOR
  • Standard library utilities
    • std::unique_lock - exclusive mutex wrapper (C++11)
    • std::shared_lock - shared mutex wrapper (C++14)
    • std:lock_guard - ownership of a mutex in a scope (C++11)
    • std::scoped_lock - ownership of multiple mutexes (avoids deadlock) (C++11)
    • experimental:scope_exit - general purpose scope guard
  • Guidelines Support Library (github: Microsoft GSL)
    • gsl::owner - a wrapper which prevents multiple ownership to an object

unique_ptr

hacking cpp: unique_ptr 1734624233373 1734624392609 1734624401102

shared_ptr

hacking cpp: shared_ownership.

1734624545626