English
Summary
Conclusions
An address doesn’t imply ownership. Every resource must have a clear party responsible for releasing it and a valid lifetime for all accesses. Containers and smart pointers express these rules in types; diagnostic tools help detect violations.
Self-check questions
- How do value, address and owner differ?
- What do
&and*mean in expressions? - Why can a non-null pointer be dangling?
- How do a pointer to const and a const pointer differ?
- What step does p+1 have?
- Can you dereference the address past the end of an array?
- What are the correct new/delete pairs?
- Why doesn’t nullptr reset other copies of an address?
- What does AddressSanitizer check?
- How do get, reset and release differ?
- What happens to a unique_ptr after a transfer?
- Why are two shared_ptr objects created from the same raw address dangerous?
- How does a strong cycle arise?
- What is weak_ptr::lock for?
- How does span differ from vector?
Review questions for the lab
- Is every pointer an owner?
- What limits pointer arithmetic?
- Why does a C string need a null?
- How does delete differ from delete[]?
- Why doesn’t setting one address to null fix all accesses?
- What does std::move transfer for a unique_ptr?
- When is get acceptable without release?
- How does weak_ptr break a strong cycle?
- Why can parent in a tree be non-owning?
- What does a successful ASan run prove, and what doesn’t it prove?
Useful links
- Smart pointers: https://learn.microsoft.com/cpp/cpp/smart-pointers-modern-cpp.
- unique_ptr: https://learn.microsoft.com/cpp/standard-library/unique-ptr-class.
- weak_ptr: https://learn.microsoft.com/cpp/standard-library/weak-ptr-class.
- ASan: https://learn.microsoft.com/cpp/sanitizers/asan.
- Guidelines: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines.