0% found this document useful (0 votes)
7 views

Smart Pointer

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)
7 views

Smart Pointer

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
You are on page 1/ 12

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