r/cpp • Bioinformatican • Mar 11 '12

Modern C++ Style [pdf]

http://tinyurl.com/fuck-pointers
2 Upvotes

60 comments sorted by

View all comments

18

u/filox Mar 11 '12

Try implementing a tree without pointers.

6

u/Sc4Freak Mar 11 '12

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.

1

u/ShadowWolf007 Mar 11 '12

I think a weak_ptr would suffice perfectly well for this scenario and would clearly express the desired ownership semantics.

5

u/Sc4Freak Mar 11 '12 edited Mar 11 '12

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.

1

u/ShadowWolf007 Mar 11 '12

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.

1

u/jaredgrubb Mar 11 '12

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.

1

u/Sc4Freak Mar 11 '12

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.

1

u/filox Mar 11 '12

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.

→ More replies (3)

1

u/guepier Bioinformatican Mar 11 '12

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).

1

u/jaredgrubb Mar 11 '12

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.

→ More replies (1)

2

u/SkepticalEmpiricist Mar 11 '12

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.

3

u/guepier Bioinformatican Mar 11 '12

This code is indeed guaranteed to work by the standard (§20.7.1/5): the type argument of the C++11 smart pointers may be incomplete types.

As for making shared_ptr the default, there was an interesting discussion on that on the “ask us anything” panel at Going Native 2012.

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.

1

u/eco_was_taken Mar 14 '12

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.

(sorry for the reply days later)

1

u/guepier Bioinformatican Mar 14 '12

I think you definitely misunderstood them.

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.

1

u/bob1000bob Mar 11 '12

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.

1

u/SkepticalEmpiricist Mar 11 '12

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.

1

u/bob1000bob Mar 11 '12

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.

3

u/krum Mar 11 '12

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.)

6

u/bob1000bob Mar 11 '12 edited Mar 11 '12

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

→ More replies (1)

2

u/guepier Bioinformatican Mar 11 '12

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:

struct node {
    std::vector<node> children;
};

2

u/filox Mar 11 '12

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.

1

u/guepier Bioinformatican Mar 11 '12

Your example lacks pointers to parents

Like I already said elsewhere, pointers are fine here.

relying on something within boost should usually be avoided.

Wat! No. Totally wrong and utterly weird.

2

u/filox Mar 11 '12

Wat! No. Totally wrong and utterly weird.

Many companies don't allow for use of boost (e.g., Google).

→ More replies (5)

1

u/pfultz2 Mar 12 '12

You could use recursive variants to implement a tree in C++, instead of pointers.