Friday, September 20, 2019

Unique Pointer (Smart Pointer)

The following example shows how to use unique_ptr which semantically 'moves' the data during assignment:


#include <iostream>
#include <memory>


using namespace std;


class MyClass
{
public:

#if COMPILE_ERROR
    MyClass
    (
        std::unique_ptr<int> const &  pOpt = std::unique_ptr<int>(nullptr) 
    ) : m_ptr(std::move(pOpt))
    {
    }
#else
    explicit MyClass
    ( 
        std::unique_ptr<int> pOpt = std::unique_ptr<int>(nullptr)
    ) : m_ptr(std::move(pOpt))
    {
        std::cout << __FUNCTION__ << "() : m_ptr=" << m_ptr.get() << std::endl;
    }

    MyClass() = delete;

#endif
    friend ostream& operator<<(ostream& os, const MyClass& c);

private:
    std::unique_ptr<int>  m_ptr;
};


template<typename T>
std::unique_ptr<T>& pass_through(std::unique_ptr<T>& p)
{
    if (p != nullptr)
        std::cout << *p << std::endl;
    else
        std::cout << "nullptr" << std::endl;
    return p;
}


ostream& operator<<(ostream& os, const MyClass& c)
{
    if (c.m_ptr != nullptr)
        return os << __FUNCTION__ << "(): " <<  *c.m_ptr;
    else
        return os << __FUNCTION__ << "(): nullptr";
}


int main()
{
    std::unique_ptr<int> pInt(new int(15));

    MyClass data();
    MyClass data2(std::move(pInt));

    pass_through(pInt);
    
    std::cout << "data = " << data << std::endl;
    std::cout << "data2 = " << data2 << std::endl;
}


MyClass() : m_ptr=0x7430d0

nullptr

data = 1

data2 = operator<<(): 15




No comments:

Post a Comment