views:

168

answers:

1

I was recently introduced to the existence of auto_ptr and shared_ptr and I have a pretty simple/naive question.

I try to implement a data structure and I need to point to the children of a Node which (are more than 1 and its) number may change. Which is the best alternative and why:

class Node
{
    public:
        // ...
        Node *children;

    private:
        //...
}

class Node
{
    public:
        // ...
        share_ptr<Node> children;

    private:
        //...
}

I am not sure, but I think auto_ptr does not work for arrays. I am not, also, sure about whether I should use double pointers. Thanks for any help.

+3  A: 

You're right that auto_ptr doesn't work for arrays. When it destroys the object it owns, it uses delete object;, so if you used new objects[whatever];, you'll get undefined behavior. Perhaps a bit more subtly, auto_ptr doesn't fit the requirements of "Copyable" (as the standard defines the term) so you can't create a container (vector, deque, list, etc.) of auto_ptr either.

A shared_ptr is for a single object as well. It's for a situation where you have shared ownership and need to delete the object only when all the owners go out of scope. Unless there's something going on that you haven't told us about, chances are pretty good that it doesn't fit your requirements very well either.

You might want to look at yet another class that may be new to you: Boost ptr_vector. At least based on what you've said, it seems to fit your requirements better than either auto_ptr or shared_ptr would.

Jerry Coffin
Thanks! So I get that I should go with either `ptr_vector` or `Node * children`. Could not I use `auto_ptr` to point to an `std::vector` of `Node`s? Furthermore, is the `Node * children` right or I should prefer `Node ** children`? I am a bit confused. Sorry for packing too many questions here.
myle
@myle: Without knowing more about what you're doing, it's hard to say for sure. Basically, a `Node *` will give you one point to an arbitrary number of Nodes, so those nodes will basically be part of their parent, not just linked to it. A `Node **` will let you have a dynamic array of pointers to nodes, but you'll have to manage the dynamic array yourself.
Jerry Coffin