c++c++11unique-ptr

How can I pass std::unique_ptr into a function


How can I pass a std::unique_ptr into a function? Lets say I have the following class:

class A
{
public:
    A(int val)
    {
        _val = val;
    }

    int GetVal() { return _val; }
private:
    int _val;
};

The following does not compile:

void MyFunc(unique_ptr<A> arg)
{
    cout << arg->GetVal() << endl;
}

int main(int argc, char* argv[])
{
    unique_ptr<A> ptr = unique_ptr<A>(new A(1234));
    MyFunc(ptr);

    return 0;
}

Why can I not pass a std::unique_ptr into a function? Surely this is the primary purpose of the construct? Or did the C++ committee intend for me to fall back to raw C-style pointers and pass it like this:

MyFunc(&(*ptr)); 

And most strangely of all, why is this an OK way of passing it? It seems horribly inconsistent:

MyFunc(unique_ptr<A>(new A(1234)));

Solution

  • There's basically two options here:

    Pass the smart pointer by reference

    void MyFunc(std::unique_ptr<A> & arg)
    {
        std::cout << arg->GetVal() << std::endl;
    }
    
    int main(int argc, char* argv[])
    {
        std::unique_ptr<A> ptr = std::unique_ptr<A>(new A(1234));
        MyFunc(ptr);
    }
    

    Move the smart pointer into the function argument

    Note that in this case, the assertion will hold!

    void MyFunc(std::unique_ptr<A> arg)
    {
        std::cout << arg->GetVal() << std::endl;
    }
    
    int main(int argc, char* argv[])
    {
        std::unique_ptr<A> ptr = std::unique_ptr<A>(new A(1234));
        MyFunc(std::move(ptr));
        assert(ptr == nullptr)
    }