Search code examples
c++standard-libraryauto-ptrhuffman-code

function wont accept iterator to auto_ptr


I wrote some flawed Huff compression code that I was trying to fix. The first thing I did was to switch the pointers to auto_ptr (There are reasons I didn't use another smart pointer). I create a vector of auto_ptr but when I try to pass an auto_ptr to a function by *(vector.begin()) it doesn't work.

My function code I'm trying to pass ownership to (it's a member function as set_node):

struct Node {
    int weight;
    char litteral;
    auto_ptr<Node> childL;
    auto_ptr<Node> childR;
    void set_node(int w, char l, auto_ptr<Node>& L(), auto_ptr<Node>& R()){
        weight = w;
        litteral = l;
        childL = L;
        childR = R;
    }
};

and this is how I try to call it (p is a node):

p.set_node(w, '*', *nodes->begin(), *(nodes->begin()+1));

This is how the vector is declared:

vector<auto_ptr<Node> >* nodes = new vector<auto_ptr<Node> >;

Solution

  • You cannot use std::auto_ptr in std::vector. You will need to find an alternative. The problem is that there is no copy in std::auto_ptr. The copy constructor is in some sense a move operation that steals the contents from the original auto pointer and moves it to the new one. That operation requires that the source is a non-const std::auto_ptr (as it removes the managed object from it).