Smart Pointers
- In Effective Modern C++ Meyers has an entire chapter on smart pointers.
- He has a list that indicates problems with raw pointers
- The declaration doesn't indicate whether it points to a sing object or to an array.
- The declaration reveals nothing about whether you should destroy what it points to when you're done using it, i.e., if the pointer owns the thing it points to.
- If you determine that you should destroy what the pointer points to, there is no way to tell how. (Delete or custom destructor)
- If you manage to find out the way to delete the way to delete the pointer, you don't know to use delete, or delete[]
- It is hard to know exactly when to delete the pointer and ensure that you destroy it exactly once.
- There is no way to ensure that the pointer is not dangling
- C++98 introduced auto_ptr but this was not well done.
- C++11 introduced unique_ptr, shared_ptr and weak_ptr.
- All of these correct most of the problems with raw pointers.
- Meyers says to not use auto_ptr, it is deprecated.
- unique_ptr is for when you want a single pointer to an object, no exceptions.
- this is a raw pointer with protection.
- It is almost as fast and as efficient as a raw pointer.
- Meyers says that without any other motivation, this is the one to use.
- shared_ptr is when you want to have more than one pointer to an object.
- This is essentially the handle class.
- Meyers says that it allocates an int count just like the handle class.
- So it takes twice as much space as a unique_ptr (ptr to data, ptr to count)
- And for parallelism, the action is atomic, so it is slower.
- weak_ptr
- Tracks when the thing it poits to has been deleted.
- These are apparently strange to work with
- And derived from shared_ptr
- cppreference.com documentation
- Shared pointers
- Relatively straightforward.
- Create them with
make_shared<type>(params)
- Cast with
*_pointer_cast(target)
- Do not delete. Not your problem.
- Other member functions
- reset(), or reset(ptr), replaces the existing pointer.
- get() returns a raw pointer.
- * and -> dereference
- use_count() returns the number of things pointing to the object.
- using it as a bool tells us if it is pointing to anything.
- After c++ 17, [] can be used if it points to an array.