#include <iostream>
#include <memory>
int main() {
int a; // this holds an integer on the stack
a = 5;
int *p; // this holds the address (location in memory) of some other integer
p = &a; // the & takes the address of a and = assignes it to p
printf("%d\n", a); // we can print a
printf("%d\n", *p); // or we can use * to get from the pointer back to what it points to
// the above variable is allocated on the "stack", and those go away when the scope exits (a scope is {})
// instead, let's make one on the heap, which sticks around until we release it:
p = new int; // now p points to an int on the heap, no longer pointing to a
*p = 7; // assign a value to this heap memory
printf("%d\n",*p);
// the problem is, we can forget to delete the int pointed to by p because
// there is no automatic delete like with a stack variable, so we have
// to delete it manually:
delete p; // but what if we forget? ...we'd get a "memory leak" which if it happens enough can kill a program
// the later C++ standards created shared_ptr to deal with this problem, and
// shared_ptr is in the std "namespace" ... which is just a way of organizing
// names so that if someone else creates something called shared_ptr in a different
// namespace we'll know which one we mean
{ // new scope
std::shared_ptr<int> p2 = std::make_shared<int>(8); // now p2 is the address of the integer on the heap holding the value 8
printf("%d\n", *p2); // can still get the value and print it
// ...but if we forget to delete it, it will be automatically deleted when the last shared_ptr referring to it goes away!
} // p2 goes away here, so the memory is freed
std::shared_ptr<int> p3;
{
std::shared_ptr<int> p2 = std::make_shared<int>(8); // same as above
p3 = p2; // but now p3 points to this value of 8 as well
} // p2 goes away, but 8 is not deleted because p3 in the outer scope still refers to it!
printf("%d\n", *p3); // print the 8
}
To embed this project on your website, copy the following code and paste it into your website's HTML: