It is best practice to chain up
new/
delete whenever possible, and not share a memory address with raw pointers.
OR....
Consider using smart pointers, they were added to the C++ stdlib to make leaks far less likely. The smart pointer object does all the memory management for you so you don't have to remember to
delete what was
newed. There are several "flavors" of smart pointers available, the two most common are
std::unique_ptr<> and
std::shared_ptr<>.
https://en.cppreference.com/w/cpp/memory
For
gits and shiggles I (crudely) rewrote the code to use shared pointers instead of raw pointers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
#include <memory>
int main()
{
// int* p1, * p2;
// I prefer to create a single variable per line
std::shared_ptr<int> p1;
std::shared_ptr<int> p2;
p1 = std::make_shared<int>(42);
p2 = p1;
std::cout << "*p1 == " << *p1 << '\t';
std::cout << "*p2 == " << *p2 << '\n';
*p2 = 53;
// could have been written using std::make_shared
// p2 = std::make_shared<int>(53);
std::cout << "*p1 == " << *p1 << '\t';
std::cout << "*p2 == " << *p2 << '\n';
p1 = std::make_shared<int>(88);
std::cout << "*p1 == " << *p1 << '\t';
std::cout << "*p2 == " << *p2 << '\n';
}
|
*p1 == 42 *p2 == 42
*p1 == 53 *p2 == 53
*p1 == 88 *p2 == 53 |
The smart pointers still need to be dereferenced directly using
operator* to get the contained data, same as with raw pointers.
But now there is no possibility of memory leaks because the smart pointers take care of memory management automatically from cradle to grave.
Because initially both smart pointers own the same object (line 14) I chose
std::shared_ptr<> instead of
std::unique_ptr<>.
This code is a trivial use of pointers so using smart pointers is kinda over-kill.