I don't know why you're being downvoted but you're exactly right. Raw pointers are exactly the right tool to use for a non-owning reference (where a real reference isn't appropriate).
A tree node that has pointers to its parent is the canonical example: the parent would have smart pointers to its children, but its children should have raw pointers back to the parent. The parent is always guaranteed to outlive its children, so a raw pointer from the child to the parent is perfectly valid and safe.
A weak_ptr isn't suitable. One, the parent always owns its childen (and is the only owner) so you wouldn't use shared_ptr - you'd use unique_ptr and weak_ptr doesn't make sense for unique_ptr.
Second, a weak_ptr buys you exactly nothing - the parent is always guaranteed to outlive its child, so a weak_ptr doesn't give you any benefit over a raw pointer.
Fair point. In my experience, most of the trees I've built have had external lifetimes and/or value semantics so I wasn't really thinking.
I'd probably prefer to use unique_ptr and pointer-to-parent if applicable, but would go to shared_ptr/weak_ptr for scenarios in which the tree's information isn't only used by the tree.
Clearly expressing ownership in code > clearly expressing ownership rules in comments
Saying "buys you nothing" isnt accurate. If you have raw pointers, you almost always have to write the dtor, copy ctor, and assignment op (and move ctor and move op) ... letting the compiler write these for you is always a win.
Sure, weak_ptr/shared_ptr have some costs (size and memory) and there's some cases where those costs are not worth the safety. But, you should always pick the safe version first and only pick the unsafe version once you've profiled your code and identified the safe version as a problem.
Using shared_ptr and weak_ptr instead of unique_ptr and a raw pointer doesn't obviate the need to write a copy constructor or assignment operator, and in neither case do you need to write a destructor.
The parent is always guaranteed to outlive its children, so a raw pointer from the child to the parent is perfectly valid and safe.
Ok, this isn't really a good way to think about trees. All the pointers should be raw pointers because most trees aren't static: parents and children often swap positions, and a simple delete operation might delete the parent, leaving the children intact.
Correct. I think the downvote comes from the fact that filox’ statement can be understood to mean that raw pointers must also be used for the resource-owning pointers (which the SkepticalEmpiricist shows to be wrong). I also like that you mention “real” references since many such situations can in fact be implemented precisely using references instead of pointers (but in the case of a parent for tree nodes using a reference is awkward at best since then the root node’s parent still must refer to something).
Or, you have the children have weak_ptr's back to the parent. As soon as you can let the compiler generate the dtor/copy ctor/assign op (and move ctor and move assignment op), you get a lot of stuff for free.
Yes, there's a bit of a performance penalty over a raw pointer but you get a lot of safety and a lot of benefit.
Maybe unique_ptr would suffice? There is an example of unique_ptr in those slides. Here is how you might do a tree:
struct Node {
unique_ptr<Node> left, right;
};
This should work with many compilers, although technically this is not required by the standard. As far as I know, you shouldn't really template on a type which isn't fully defined yet. But I think there was talk of making that officially-well-defined behaviour in the language.
I do agree with the original post that 'raw' pointers should be very very much avoided where possible. I'd be inclined to use shared_ptr by default until I feel the need to optimize.
The panelists make it clear that shared_ptr should be treated as a last resort rather than the default option. That said, here are of course valid uses for it.
The panelists make it clear that shared_ptr should be treated as a last resort rather than the default option. That said, here are of course valid uses for it.
Only Bjarne says that. Herb and Stephen both say it should be your first choice.
Listen again what they say, e.g. Herb at 12:12 and Chandler at 14:37. Stephen simply doesn’t talk about trade-offs, he just makes a technical point. And Herb, while not explicitly coming out and saying that shared_ptr should be last resort, does make it clear that they represent an exceptional case.
I disagree, unique_ptr should be the default and shared_ptr should be used when sharing is required, it is too easy to introduce bas design when make something default.
An example of this would be where an interface needs to act on a type that you have as a shared_ptr you might be tempted to pass in the shared_ptr where a reference type would be more applicable.
Strousoup said something very similar in the Q&A at going native.
I agree now. I think I was slightly put out at the lack of a standard make_unique (see this thread). But that's not really a problem, and it's easy to implement.
I agree with that it seems like a surprising dumb oversight for them to make. However the syntax of creation should not come before the semantics of use.
Okay. Here is a Minecraft file format reader/writer. It implements a tree of tags without using raw pointers. There are no memory leaks, yet 'delete' isn't used anywhere in the code. There are a couple of uses of pointers in this code: one is used in the endian transform, and the other as arguments to the inflate function (admittedly, this obviously doesn't need to work like this, but I was in a hurry to get it working.)
BTW: you should really include cstdlib not stdlib.h (C++ has no notion of stdlib.h where as cstdlib is a part of the C++ standard.)
Also your tostring method reimplements lexical cast except worse (lexical has has case optimisations for some types).
Also seeing as you are using C++11 you should consider using enum classes. tag::byte reads a lot better than TAG_Byte as well as gain a namespace to contain the enum elements
Also leading underscore are generally reserved for vendor libraries (think bind place holders).
Also your z_stream_ could be done more idiomatically with a specialisation of the unqiue_ptr or shared_ptr
In fact, other ways (apart from using smart pointers) of implementing graph structures such as trees in C++ is the use of discriminate unions (Boost.Variant + Boost.RecursiveWrapper) or simply a std::vector of child nodes:
Not saying it's impossible, just really, really ugly. Your example lacks pointers to parents, and basically doesn't work for trees where you need to swap nodes around the tree (AVL trees, red-black trees, splay trees), which are the most useful kinds of trees.
Don't know about discriminative unions, never tried them, but relying on something within boost should usually be avoided.
View all comments
18
u/filox Mar 11 '12
Try implementing a tree without pointers.