smart_pointers.cc 2.26 KB
/*
 * A simple overview of the smart pointers, unique_ptr and shared_ptr
 * Both handles ownership of dynamically allocated memory and will
 * automatically delete the internal pointer when they are destroyed.
 * unique_ptr has unique ownership (only one unique_ptr handles one 
 * resource) while several shared_ptrs can handle the same resource.
 */
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
// Terrible function signature, the return value
// could be both a pointer to some resource that
// will be taken care of and a pointer that has
// to be deallocated after use.
int * get()
{
    return new int{};
}

struct Type
{
    Type(int a): data{a} {}
    ~Type() { cout << "Destruerar " << data << endl; }
    int data;
};

// Takes a unique_ptr by value. Due to the missing copy constructor,
// the user of this function has to explicitly move the resource during
// call.
void fun( unique_ptr<int> p )
{
    cout << *p << endl;
}

int main()
{

    // both unique_ptr and shared_ptr can be initialized using constructor
    // that takes a raw pointer and using helper function make_<ptr-type>.
    // The helper function takes the arguments needed by the constructor
    // for the pointed-to type.
    unique_ptr<int> ptr;
    ptr = make_unique<int>(4);
    // auto tells the compiler to look at the value used as initialization
    // and choose that type for p. You always need to initialize your
    // variable when you use auto. See https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/ for a discussion on when to use auto.
    auto p = make_unique<Type>(4);
    {
        auto pt = make_unique<Type>(5);
    }
    // One way of transferring ownership of the internal resource
    unique_ptr<Type> p2 { p.release() };
    // A bit more explicit
    unique_ptr<Type> pp {move(p2)};
    // also supports move assignment
    p2 = move(pp);

    auto p3 = make_unique<int>();
    // Transfer ownership to fun
    fun(move(p3));

    // shared_ptr. The resource will only be removed when the last
    // shared_ptr for that resource goes out of scope.
    {
        shared_ptr<Type> sp { make_shared<Type>(5) };
        {
            shared_ptr<Type> sp2 {sp};
            {
                auto sp3 = sp;
            }
        }
    } 

}