/******************************************************************************
Welcome to code of Lập trình - Điện tử
Series: C++
Author: Nghĩa Taarabt
*******************************************************************************/
#include <iostream>
using namespace std;
int main()
{
//Solution 3
//For multiple pointers pointing to the same address , Make sure there is
//one clear pointer (master pointer) that owns the memory ( responsible for releasing when
// necessary) , other pointers should only be able to dereference when the master pointer is valid
std::cout << std::endl;
std::cout << "Solution 3 : " << std::endl;
int * p_number8 {new int{382}};// Let's say p_number8 is the master pointer
int * p_number9 {p_number8};
//Dereference the pointers and use them
std::cout << "p_number8 - " << p_number8 << " - " << *p_number8 << std::endl;
if(!(p_number8 == nullptr))
{ // Only use slave pointers when master pointer is valid
std::cout<< "p_number9 - " << p_number9 << " - " << *p_number9 << std::endl;
}
delete p_number8; // Master releases the memory
p_number8 = nullptr;
if(!(p_number8 == nullptr))
{
// Only use slave pointers when master pointer is valid
std::cout<< "p_number9 - " << p_number9 << " - " << *p_number9 << std::endl;
}
else
{
std::cerr << "WARNING : Trying to use an invalid pointer" << std::endl;
}
}