News for hackers. Stuff that matters.
Re:Elements of Modern C++ Style by obiterdictum on Saturday October 29, 2011 @10:49AM (#3171979)
We have just started using some C++11 features, and with new features come new traps and potential complexities, as you'd expect with C++.

A few examples:

1. Implicit lambdas ("[=]") capture "this" pointer for data members, if you capture a shared pointer and let the lambda object leave the scope, the shared pointer won't be copied (http://stackoverflow.com/q/7764564/23643), which may create unpleasant results, like code blowing up in your face.

2. Overuse of "auto" (not exclusive to C++) may make the code harder to read, especially if storing a result returned from a function. You can't tell if the return value is a smart pointer or a raw pointer, value or a reference, so you can't figure ownership semantics just by looking at the local code.

3. Move constructors/assignment operators are a bit of a black magic, especially with regard to suppressing default implementation (http://mmocny.wordpress.com/2010/12/09/implicit-move-wont-go) and exception safety (http://cpp-next.com/archive/2009/10/exceptionally-moving). I would refrain from using it, until I fully understand it.

With that said, most of C++11 is a welcome change and makes C++ more pleasant to write, but, as always, you have to have your guard up and use new features judiciously.

Re:Elements of Modern C++ Style by ajross on Saturday October 29, 2011 @11:17AM (#3172043)
C++ always seems to lead to traps. In point #2, you're obviously right about the micro-coding/readability point. But the premise is kind of scary: you're dealing with a code base where the ownership semantics of an object are captured only by a function return type? Yikes. That's a framework issue: if everyone working on the source isn't 100% sure what that return means, you're guaranteed to get bugs with or without auto. Non-trivial ownership/allocation/copy semantics (i.e. anything other than "on the stack" or "operator new") are deep C++ voodoo, not something you worry about in passing as a readability thing.
Re:Elements of Modern C++ Style by jemfinch on Saturday October 29, 2011 @12:35PM (#3172201)
At least you can express ownership semantics in C++ code, using constructs like `unique_ptr`, `scoped_ptr`, and `shared_ptr`. In a garbage collected language, nothing expresses ownership, and so while you not be at risk of memory leaks, you're still vulnerable to all the other bugs that come with aliasing mutable objects.

The "framework issue" you describe is solved precisely by specifying ownership semantics in terms of smart pointer return values. The way everyone becomes "100% sure what that return means" is by whether it returns a `unique_ptr` or a `shared_ptr`. The OP is simply complaining that `auto` takes away that local information on ownership.

`operator new()` is only trivial by virtue of not specifying anything at all about ownership. `scoped_ptr` and `shared_ptr` and `unique_ptr` are each specifying different, more restricted, but still trivial ownership semantics. They aren't "deep C++ voodoo" in the least. Your post smacks of someone who doesn't actually write C++ for a living.

Re:Elements of Modern C++ Style by oconnore on Saturday October 29, 2011 @03:56PM (#3172651)
> In a garbage collected language, nothing expresses ownership, and so while you not be at risk of memory leaks, you're still vulnerable to all the other bugs that come with aliasing mutable objects.

You are conflating required language features with proper API design and documentation. I don't need '(unique|scoped|shared)_ptr' to refrain from aliasing mutable types, or to document my code properly on the rare occasion when I am required to.

Re:Elements of Modern C++ Style by cpeterso on Saturday October 29, 2011 @11:07PM (#3173530)
I wish C++11 added syntactic sugar for the smart pointer classes like scoped_ptr, shared_ptr, and unique_ptr. I would rather see new operators (like Microsoft C++/CLI's ^ and %) than even more templated code. Compare something like:

  int^ foo(int% bar);
versus:

  std::unique_ptr<int> foo(std::shared_ptr<int> bar);
Smart pointers have long been available in boost and are required for writing safe code, but they make code unreadable (even after typedefs).
Re:Elements of Modern C++ Style by pyrtsa on Sunday October 30, 2011 @08:44AM (#3174229)
I don't think introducing more syntax to the language for a feature that ultimately is a library solution, is a sustainable way to go.

But if you really need a compact notation for smart pointers, you'll get pretty close by using template aliases, e.g.

    template <typename T> using up = std::unique_ptr<T>;
    template <typename T> using sp = std::shared_ptr<T>;
    // ...
    up<int> foo(sp<int> bar) {
        return bar ? up<int>(new int(*bar)) : nullptr;
    }
Re:Elements of Modern C++ Style by thwest on Sunday October 30, 2011 @10:50AM (#3174495)
Oh C++11 has template typedefs? Time to migrate my project.
Re:Elements of Modern C++ Style by apaprocki on Saturday October 29, 2011 @12:33PM (#3172198)
2. I'm sure IDEs/editors will start to implement features to grok object output and/or do static analysis to show you what type auto implies. It isn't necessarily easy but it seems like the feature everyone would want. You could even produce a "de-auto" button that would toggle between auto and the substituted real type for readability.

3. Move operations are completely welcome as far as I'm concerned. I recently hit some performance problems which beg for move or emplace semantics. Most people don't realize the amount of copies they are making when using STL containers. These semantics will allow code to ensure only one instance of a value type is ever created when, say, inserting into a map. I feel like some people resort to going back to hand-rolled data structures or raw pointers when performance is critical because the current containers are missing this.

Re:Elements of Modern C++ Style by CJefferson on Saturday October 29, 2011 @02:21PM (#3172436)
In templates, it is almost impossible to remove the 'auto'. Even something simple like:

    template<typename T>
    void f(T t1, T t2)
    { auto sum = t1 + t2; }
There is nothing to replace auto with. Similar things apply to most templated functions. Of course outside of templates things get much easier, but I wouldn't expect to see quite so many autos.
Re:Elements of Modern C++ Style by dilap on Saturday October 29, 2011 @03:07PM (#3172541)
True, but at least screw-ups will be noticed at compile time. And how would you even write this snippet, pre auto?!

(I think you'd either just assume t1 + t2 was T, or you'd have to go thru less-general, even-less-clear, gymnastics (like having some structure defined like get_sum_type<T,T>::thetype sum = t1 + t2).)

Re:Elements of Modern C++ Style by CJefferson on Saturday October 29, 2011 @06:15PM (#3172959)
Exactly right, in C++03 this kind of stuff was really horrible.

In general people (the STL, and all Maths code I've ever read), will just assume that the type is T. For things like iterators, you have to do things like:

    typename std::vector<T>::const_iterator it = v.begin();
(That typename has to be there, for stupid C++ reasons). Being able to reduce that to:

    auto it = v.begin();
Is probably the most visible advantages to C++11 is one of the most obvious improvements for many programers.
Re:Elements of Modern C++ Style by koenigdavidmj on Saturday October 29, 2011 @04:45PM (#3172757)
>And how would you even write this snippet, pre auto?!

  typeof(t1 + t2) sum = t1 + t2;
Re:Elements of Modern C++ Style by dilap on Saturday October 29, 2011 @05:43PM (#3172887)
That's cheating! I meant how would you write it pre-C++11 extensions (and also not using the earlier GCC typeof extension). decltype is just a slightly different form of auto. :)
Re:Elements of Modern C++ Style by koenigdavidmj on Saturday October 29, 2011 @04:50PM (#3172772)
That should be decltype, not typeof, btw
Re:Elements of Modern C++ Style by dilap on Saturday October 29, 2011 @11:31AM (#3172069)
Coming from a dynamically-typed language perspective, (2) seems like incredibly not a big deal. If you're unclear on the return type, just look at the declaration of the function that's being called.

Compare this to, e.g., Python, where you have to look at the actual definition of the function being called (and maybe eve n the definition of functions it calls, and so on), which is way worse.

Re:Elements of Modern C++ Style by rayiner on Saturday October 29, 2011 @01:19PM (#3172300)
Dynamically typed languages respond to the problem in (2) by keeping typing simple. C++'s proliferation of multiple ways to do the same thing (regular pointer, smart pointer, reference, etc) and multiplicity of ownership rule (no GC) cuts across that.
Re:Elements of Modern C++ Style by dilap on Saturday October 29, 2011 @03:02PM (#3172529)
It's certainly true that dynamic, high-level languages save you from having to worry about ownership-semantics, but you still care a lot about the return-type (e.g., am I getting back an int, a str, a set, a dict, a simple list, a generator, &c &c &c)!

You care about this; either it must be obvious (e.g., fairly obvious with a function like len()), or you have to look it up in the documentation or comments of the function. If it's not documented, you have to try to figure it out from the function body, which is often non-trivial. This is why you'll typically see what amounts informal type annotations in the comments of functions of mature code.

Despite all this, many people feel that the flexibility of not having to specify types is a net-win.

C++ "auto" adds some of the convenience, but at a much lower cost in readibility, since when you see something like

  auto x = foo.gimmeBar();
you can find out the type of x immediately just by looking at the definition of gimmeBar() (with IDE support, this could even be zero-effort (i.e., it could show a little grey popup bubble with the deduced type); even with something old-fashioned like emacs+ctags, it's just a hop-skip-and-a-jump away).

  *
By the way, regarding ownership-semantics, it's true they could be a massive PITA pre-C++11, and (sort of analogously to the what-are-the-types-in-a-dynamic-language situation) you'd often have to fall back to relying on comments to know what was going on. If they're weren't comments and you were getting back a raw pointer, well...that could be rough.

This is a problem that can be fixed with library support (for smart pointers) and disciplined coding -- i.e., using the smart pointers. For a good example of this working really well in practice, see Objective-C.

C++11 helps because it gives us built-in library support, and will hopefully provide the community motivation for the convention/discipline of actually using the libs.

(This pointer-ownership stuff is pretty much orthogonal to auto, though, IMO.)

Re:Elements of Modern C++ Style by Someone on Saturday October 29, 2011 @07:09PM (#3173091)
"It's certainly true that dynamic, high-level languages save you from having to worry about ownership-semantics"

What languages are you thinking about? In most languages I can think of as being "dynamic, high-level", state is mutable. So, if a method on an object returns a collection, and the caller wants to keep the result around, the programmer will have to somehow know whether the collection that the method returned was freshly allocated or internal to the object, whether it is modifiable, how long the content of the collection is guaranteed to be stay constant (e.g: what happens when I append to a list from a loop that iterates over it?), etc.

Similarly, if one passes an object to say a constructor, one should know whether the constructed object holds a reference to that object, thus sort-of claiming ownership.

It is true, though, that whenever I think about such issues, I am amazed that these things so rarely lead to problems. Apparently, all programmers share a single mental model for the 'natural' ownership policies.

Re:Elements of Modern C++ Style by frou_dh on Saturday October 29, 2011 @07:47PM (#3173163)
Enter Clojure with its first-class persistent + immutable collections!
Re:Elements of Modern C++ Style by dilap on Monday October 31, 2011 @05:59PM (#3179314)
Yup, you're right -- I was just talking about deallocation, but more than that matters in a mainstream, side-effecty language, as you point out.
Re:Elements of Modern C++ Style by rayiner on Saturday October 29, 2011 @05:21PM (#3172843)
> but you still care a lot about the return-type (e.g., am I getting back an int, a str, a set, a dict, a simple list, a generator,

You do, but convention gives you a lot more context. If, by the nature of the function, I know I'm expecting a list, I know I'm going to get a list. I'm not going to get a pointer to a list versus a reference to a list versus a smart pointer to a list versus an iterator pointing into a list, etc.

Compare the C++ STL to Common Lisp's standard library. A given STL function might take or return an iterator, an iterator pointing to a pair, a pointer, or a value. In the Common Lisp standard library, something is going to return either a value or a collection and its obvious from context which it is going to do.

Re:Elements of Modern C++ Style by dilap on Saturday October 29, 2011 @07:14PM (#3173103)
I think you're sugar-coating a bit -- at least for Python, any function that might return a list could also reasonably return a generator, and might even return a tuple or a set.

I can't speak to common lisp, but I have a fair amount of experience with Python and with the STL (and other stuff, but those two most of all), and I've found the STL to be one of best-designed, most predictable, and easy to use libraries out there. YMMV, of course.

(BTW, an iterator is just a generalization of the concept of a pointer; i.e., a pointer is an iterator.)

Re:Elements of Modern C++ Style by alecthomas on Saturday October 29, 2011 @10:58AM (#3172003)
Good points. Re. 2, we decided to only use auto for iterators, which eradicated a large amount of boilerplate without being too confusing.
Re:Elements of Modern C++ Style by iam on Saturday October 29, 2011 @11:09AM (#3172026)
Wow that's interesting. Never realized lambdas capture "this" and not the actual data members itself!

That also means you can get in big trouble if the object that got captured was deleted, ouch.

Re:Elements of Modern C++ Style by ajross on Saturday October 29, 2011 @11:18AM (#3172046)
This is why Lisp never had manual allocation. It's a booby trap for a new generation, kind of like the collision between heap allocation and exceptions was in our youth.