Smart Pointers
Fundamentals on Computing for Robotics, Graphics and Computer Vision
Darío Suárez - Adolfo Muñoz
Dynamic Memory Issues
- Each
new
always requires a matching delete
- Possible Issues:
- Access an unitilized pointer
- Memory leaks: unreachable objects in the heap
- Dangling pointers: pointers to already released objects
- Multiple deletion: calling delete several times for the same object
Possible solution
- How we can automatically guarantee the release of the object?
- Think in objects in the stack and RAII (Resource Adquisition Is Initialization)
Quiz: What are the scopes within this program
detour: Resource Adquisition Is Initialization
- RAII: C++ idiom that joins the lifetime
of a resource (memory, file, socket, ...) to that of an object
- Is
ptr
object always released?
Use of ToyPtr
How many times is called delete
?
std::unique_ptr<T>
- Solution for single ownership of an object through a pointer
- Dealocates when going out of scope
- Cannot be copied and can be moved
- Use std::make_unique to create them
std::shared_ptr<T>
- Solution for multiple pointers to the same object
- Internally counts the number of refereces to the object
- Allocation increases the counter, deallocation reduces the counter. When
reaching 0, the object is deallocated
- Use std::make_shared to create them