#include <cstdio> // printf
#include <memory> // std::shared_ptr
#include <string> // std::string

int main() {
    
    int *p = new int(8); // regular pointer to an int on the heap (have to delete later)
    auto p2 = std::make_shared<int>(9); // shared pointer to another int on the heap, will auto-destruct
    // note: auto above could also be std::shared_ptr<int> *p2 = ...
    printf("%d %d\n", *p, *p2);
    
    // now we want to allocate variables that hold the locations of the pointer above
    // these are "pointers to pointers"
    int **p3 = &p; // take the address of pointer p and put that in p3
    auto p4 = &p2; // take the address of shared_ptr p2 and put it in p4
    
    // we can still get at the values but two levels of dereference are required:
    printf("%d %d\n", **p3, **p4);
    
    // but what if the thing is a struct (or class) and not just an int?
    // (back to discussing pointers now, not pointers-to-pointers)
    struct A 
    {
        // & in this context is NOT taking the address of something, but instead
        // declaring a "reference" which is similar to a pointer but can't have
        // a null value ... different topic, and const is also a different topic
        A(const int &_val1, const std::string &_val2) : val1(_val1), val2(_val2) {}
        int val1;
        std::string val2;
    };
    
    auto p5 = new A(10,"a dog"); // regular pointer
    auto p6 = std::make_shared<A>(11,"a cat"); // shared_ptr
    
    // to get at the parts of A through the pointer, we could use . (dot)
    printf("%d %s\n", (*p5).val1, (*p6).val2.c_str()); // c_str() gets the %s-compatible version of the string
    // or we could use -> which is just a prettier convenient syntax:
    printf("%d %s\n", p5->val1, p6->val2.c_str());
    // note that in the above prints I'm mixing so we have 10/cat ... one from each object
    
    
    // delete regular pointers, otherwise we cause memory leaks...
    delete p;
    delete p5;
    
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: