0% found this document useful (0 votes)
29 views12 pages

Smart Pointer

The document discusses smart pointers in C++, highlighting the issues with traditional pointers such as memory management and ownership confusion. It introduces unique_ptr for single ownership and shared_ptr for multiple ownership with reference counting, and also mentions weak_ptr for accessing shared_ptr objects without affecting their reference count. The document provides examples of creating and using these smart pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views12 pages

Smart Pointer

The document discusses smart pointers in C++, highlighting the issues with traditional pointers such as memory management and ownership confusion. It introduces unique_ptr for single ownership and shared_ptr for multiple ownership with reference counting, and also mentions weak_ptr for accessing shared_ptr objects without affecting their reference count. The document provides examples of creating and using these smart pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Smart pointer

https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=vs-2019
Using pointer to create object
Problem with pointers

1. We may forget to call delete (developers are still human


afterall)
2. Object is created from another function, leads to confusion in
ownership
Who should call destructor?
Or even worse, do we have the right to call the destructor?
unique_ptr
Creating a pointer to class Category
Access to methods & properties like normal pointer
Meaning of unique_ptr

Allows exactly one owner of the underlying pointer


If we want to have multiple owner, use shared_ptr
Reference-counted smart pointer
shared_ptr
Creating shared pointer

When instance count reaches 0, the object is destroyed and its memory deallocated
Question

What if we just want to access the underlying object of a


shared_ptr without causing the reference count to be
incremented?

==> weak_ptr
Creating weak_ptr
Using weak_ptr for iterating

You might also like