Using Pointers
At all costs, use smart pointers.
You can you new
to create a new instance of a type and allocate that memory on the heap. You then need to use delete
to deallocate that memory and guarentee that you won't have a memory leak. In C++, smart pointers can be used to manage the calls to new
and delete
without using them directly.
To get access to smart pointers #include <memory>
std::unique_ptr<T>
: This is a scoped pointer so when it goes out of scope it's memory is deleted. You may pass the type of the pointer as a template argumentT
. You can't copy aunique_ptr
. The preferred way to create aunique_ptr
is to usestd::make_unique
std::shared_ptr<T>
: This is a pointer that remains active until the number of references to that pointer becomes zero. You may pass the type of the pointer as a template argumentT
. The preferred way to create ashared_ptr
is to usestd::make_shared
. When you assign ashared_ptr
to anothershared_ptr
it increases the reference count.std::weak_ptr<T>
: Can be used in conjuction with ashared_ptr
but doesn't increase the reference count so doesn't affect the lifetime of the pointer's underlying entity.
Function Pointers
When declaring a function pointer it's best to use the std::function<int(void)>
syntax as opposed to the C-style int (*x)()
syntax.
However, when using member function pointers I have found this difficult, instead use int (A::*x)(void)
and call the function pointer with std::invoke
.
ADDITIONAL RESOURCES
- https://www.learncpp.com/cpp-tutorial/function-pointers/
- https://stackoverflow.com/questions/12662891/how-can-i-pass-a-member-function-where-a-free-function-is-expected How to declare member function pointers
- https://stackoverflow.com/questions/2402579/function-pointer-to-member-function Use
std::invoke
for to call member function pointers - https://stackoverflow.com/questions/12189057/how-to-call-through-a-member-function-pointer C++ reference documentation
- https://en.cppreference.com/w/cpp/utility/functional/invoke
- https://en.cppreference.com/w/cpp/utility/functional/function
- https://en.cppreference.com/w/cpp/utility/functional/mem_fn
- https://en.cppreference.com/w/cpp/utility/functional/bind