Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
×
Programming Software Upgrades

Biggest Changes In C++11 (and Why You Should Care) 385

Esther Schindler writes "It's been 13 years since the first iteration of the C++ language. Danny Kalev, a former member of the C++ standards committee, explains how the programming language has been improved and how it can help you write better code."
This discussion has been archived. No new comments can be posted.

Biggest Changes In C++11 (and Why You Should Care)

Comments Filter:
  • 13 years? (Score:2, Interesting)

    by undulato ( 2146486 )
    I could've sworn I was using it before then.. perhaps it was all just a bad dream?
    • A post under you already explained it: it refers to the first ISO standard for C++. And yeah, I thought the same thing: "Really? Only 13 years?"

    • Re:13 years? (Score:4, Informative)

      by Lord Lode ( 1290856 ) on Tuesday June 21, 2011 @08:00AM (#36511356)

      The previous C++ standard, C++98, is 13 years old, as the name implies.

  • 13 years? (Score:5, Informative)

    by Meneth ( 872868 ) on Tuesday June 21, 2011 @07:26AM (#36511038)
    C++ has been around for at least 28 years. From Wikipedia: "It was renamed C++ in 1983."

    The article is probably referring to the first finished C++ ISO standard, 14882:1998. Hardly the "first iteration" of the language.

  • Nice but... (Score:3, Interesting)

    by genjix ( 959457 ) on Tuesday June 21, 2011 @07:32AM (#36511080)

    Would love to use these features in the new C++, but unfortunately none of the major compilers support the new for-syntax, in class initialization, deleting members and explicit specification of base class methods.

    Also I totally don't understand why enum class no longer casts to ints... it totally makes using binary flags impossible unless I revert back to using the old style enums. But then I need to do the ugly namespace myenums { enum myenum { foo = 4, bar = 8 ... }; } hack which makes nesting inside classes impossible -_-

    • Re: (Score:2, Insightful)

      by daid303 ( 843777 )

      If you are putting binary flags in enums then you are using them wrong. And that's why you are no longer allowed to do so. It's a GOOD thing.

      You want bitfields: http://msdn.microsoft.com/en-us/library/ewwyfdbe(v=vs.71).aspx [microsoft.com]

      • Re:Nice but... (Score:4, Insightful)

        by Arlet ( 29997 ) on Tuesday June 21, 2011 @07:58AM (#36511340)

        Bitfields are not as flexible when you want to change several different bits (belonging to different fields) in a word using a single write.

      • I was under the impression that bitfield layout was implementation-defined, and that's undesirable if I want my project to compile on different architectures. The page you linked includes the phrase "Microsoft Specific" around anything mentioning layout, which illustrates my point.

        I was also under the impression that code generated by compilers for reading and writing bitfields was still dog slow. Has this changed?

        • by daid303 ( 843777 )

          You are basically saying. "I don't want C++, I want C!"

          • by tepples ( 727027 )
            So how would you recommend writing a parser for a binary file format that uses bitfields without this parser breaking on another platform? Perhaps if C is the best way to write such a parser, I should write this parser in C and the rest of the program in C++. Is that what you're basically saying?
    • Re: (Score:2, Interesting)

      by Anonymous Coward

      Would love to use these features in the new C++,...

      Why? What is it about these new features that will make your job easier, your code more reliable, and easier to be maintained? Or do you just want to use those features because they're "new" - for C++ that is?

      As a long time C++ guy (Borland C++ days), I look at some of these features and think "so what?" (Lambda functions, please.) I'll probably never use them. IMHO the last truly useful feature that C++ added was Templates which lead to the STL and made my life much easier - after I got the hang of the way

      • Re:Nice but... (Score:5, Insightful)

        by DrXym ( 126579 ) on Tuesday June 21, 2011 @08:22AM (#36511618)
        Templates are fine for little classes but they got so abused by STL that it was not uncommon to see trivial syntax errors turn into enormous cryptic compiler errors spanning multiple lines of nested templates and typedefs, half of whom you'd never heard of. After poring over this enormous error for minutes or longer you might eventually discover you missed a * off some declaration.
        • This is definitely true. Concepts were supposed to fix this problem, but they were booted out at the last minute. Like most compiler errors though, you start associating those walls of text with common errors after a few times. STL isn't the worst offender by far in my opinion though, boost is. Most of Boost is hard to really consider C++ anymore, its template meta programming. C++ is there in the core, but if you show a circa 1998 (IE pre-templates) developer most boost libraries, they probably wouldn't re

      • At least one feature in C++ 2011 (no, not C++11, they decided to make the name Y2K compliant this time) is useful: the auto type. If you've ever written a loop using foo::bar::iterator and had to split the loop over two lines because the iterator type is so long, you'll appreciate being able to do:

        for (auto i=collection.begin(), e=collection.end() ; i!=e ; ++i)

        Strong typing without type inference is just a stupid idea that should never have been allowed in a production language.

        • by fnj ( 64210 )

          You're right, that is very cool.

        • they decided to make the name Y2K compliant this time

          Yes, because a lot of people might be confused, thinking the standard came out in 1911. ;-)

          Regarding the type inference, I always found that to be a glaring deficiency in STL. I always thought Borland's style of implementation was much better to use, although I can understand it wasn't as flexible or fast as templates. I did the same thing in my own class library back before I used templates (and they were standard), so I could do for-loops like this:

          f

        • by mmcuh ( 1088773 )

          If your collection type has .begin() and .end() you can do

          for (auto& v : collection) { ... }

          ...and 'v' will be a reference to the value_type of the collection that refers to the element currently being iterated over. It's basically short for

          for (auto i = collection.begin(); i != collection.end(); ++i) { auto& v = *i; ... }

          You can of course also use it without the &, but then you make a local copy of every element.

      • by gerddie ( 173963 )

        As a long time C++ guy (Borland C++ days), I look at some of these features and think "so what?" (Lambda functions, please.) [...] the STL and made my life much easier - after I got the hang of the way the STL implemented things such as "iterators" and the gotchas associated with them.

        When you use iterators, then you probably use algorithms like transform or for_each. for these, lambdas are a perfect supplement.

      • Would love to use these features in the new C++,...

        Why? What is it about these new features that will make your job easier, your code more reliable, and easier to be maintained? Or do you just want to use those features because they're "new" - for C++ that is?

        As a long time C++ guy (Borland C++ days), I look at some of these features and think "so what?" (Lambda functions, please.) I'll probably never use them. IMHO the last truly useful feature that C++ added was Templates which lead to the STL and made my life much easier... I stopped reading at this point... .

        Let me stop you right there for a second. Proper utilization of lambdas and closures pretty much make a lot of design patterns (template, strategy, visitor, for example) unnecessary in many contexts. This obviously will have an impact in how you write/use templates. Furthermore, lambdas and closures help with shrinking class hierarchies even further than delegation alone.

        Yes, we had functors before, but now you neither need to define functors classes/structs defining 'operator()', nor have to invoke new o

    • Re:Nice but... (Score:5, Informative)

      by mmcuh ( 1088773 ) on Tuesday June 21, 2011 @08:04AM (#36511412)
      GCC, which is probably the most used C++ compiler, supports the new for-syntax since 4.6, deleted member functions since 4.4, and explicit virtual overrides in the 4.7 development series.
    • by Mr Z ( 6791 )

      You can do this in C++ pretty easily by overloading the bitwise OR operator on the enum. Thus, when you have an enum type that you know is safe to manipulate as a set of orthogonal (or mostly orthogonal) bitfield values (such as the macros that define flags for open(), for example), you can add the appropriate "operator|" to work on that type.

      Example:

      #include <iostream>

      using namespace std;

      enum foo
      {

      • FRED = 1,
        WILMA = 2,
        BARNEY = 4,
        BETTY = 8

      };

      foo operator | (foo

  • Cruft removed? (Score:5, Insightful)

    by kikito ( 971480 ) on Tuesday June 21, 2011 @07:36AM (#36511118) Homepage

    I really like that they added new stuff to the language but ...

    Have they *removed* anything at all from it? That's the only way I could get interested in that language again.

    • Have they *removed* anything at all from it?

      They can't because it would break people's code and most people get upset when that happens.

      In a Google Talk about the Go language, Rob Pike make a snide remark about how they made the recent iteration of Go smaller unlike some other languages. The only reason they can get away with that is because there's very little Go code out there.

      In contrast, there's tons of C++ and Java code out there. Both languages have cruft that I'd like to see removed too, but it

      • They can't because it would break people's code

        Then perhaps C++ and Java are overdue for a flag day [catb.org]. Visual Basic had one from VB6 to VB.NET, and Python more recently had one from Python 2 to Python 3.

      • by kikito ( 971480 )

        Adding new features makes the code non-backwards compatible. Removing them does the same thing.

        I've seen it happen in other languages (ruby, for example) and it wasn't the end of the world. If you really, really need to keep compiling old code, you just use an older compiler.

  • I am glad that C++ is still evolving. That last major improvement I remember was the addition of the string class. Then shortly after that my professional focus moved away from C and C++ and towards higher level languages (.NET, PHP, Python, Java, etc...). I just recently started my own personal project so I decided to relearn C++ again, and I noticed there is a fair amount of new stuff that wasn't there before (or I was never taught)

  • Lambda expressions!
  • Looks like C# from a few years ago. Honestly, it's really good that they're moving C++ forward, it's been lacking these features when other languages have embraced them for some time. I see they still use a plethora of ugly ass underbars, though.

    • by glwtta ( 532858 )
      I like the underbars, always makes me feel "closer to the hardware" when I see a lot of them.

      There's not reason for all languages to look the same.
      • by fitten ( 521191 )

        It makes me feel like I'm still programming in the 1980s. It's old and ugly. It's not a required "look", it's just an ancient custom. The compiler works just fine without underbars in names.

    • ..Different languages are different for a reason, they do different jobs ...

      C# is trying to be the universal very high level language that embraces all paradigms and can be used for everything ...
      C is still a low level language allowing to program low level

      C++ is stuck in the middle and so should cover the ground where you want to abstract away from the machine, but don't want a VM getting in the way, if it moves too far towards C# is will start to be ignored ...

      Both C# and C++ seem to be falling into the t

      • by fnj ( 64210 )

        I don't think there is any danger of that. You can make a C++ program just as low level as one in C, if you want. You can still compile any C code with a C++ compiler in C++ mode with generally only very minor tweaks to the expressions, and none of the tweaks changing the binary code generated. You can use as much of the added C++ features as you want; anywhere from none of them to all of them. In an ideal world there would be no reason to use a straight C compiler any more. The ways real life departs

        • by Arlet ( 29997 )

          You can still compile any C code with a C++ compiler in C++ mode

          Except when the C code uses C++ keywords. Words like new, this and delete are common enough that there are plenty of C programs using them.

          Another good reason to use a C compiler to compile C code is that the compiler is much simpler, and most likely has fewer bugs.

      • by tepples ( 727027 )

        C# is trying to be the universal very high level language that embraces all paradigms and can be used for everything

        ...except non-PC, non-Microsoft platforms. (For example, MonoTouch and Mono for Android are still priced prohibitively for hobbyists.)

  • But... (Score:5, Insightful)

    by DeathToBill ( 601486 ) on Tuesday June 21, 2011 @07:41AM (#36511172) Journal

    This is news for nerds. Stuff that matters. I thought /. abandoned this stuff ages ago...

    • by geekoid ( 135745 )

      No, not at all. There are just as many articles like this as there was 12 years ago... there's just a lot more of political crap, so the ration had changed.

  • by hal2814 ( 725639 ) on Tuesday June 21, 2011 @07:47AM (#36511216)
    C++ goes all the way to 11. It's one louder than other languages.
  • by Errol backfiring ( 1280012 ) on Tuesday June 21, 2011 @08:01AM (#36511374) Journal
    If the "alternative syntax" from PHP were allowed, the language could even become legible. What I see is still a write-only language.
    • LOL. PHP as a comparison for readability. $That's->rich();
  • by Alistair Hutton ( 889794 ) on Tuesday June 21, 2011 @08:37AM (#36511760) Homepage
    I love had back in the day C++ advocate sneered at ADA due to that fact that ADA was "designed by committee". Now C++ is the ultimate example of a design by committee language. And that committee is huge.
    • by rmstar ( 114746 )

      Now C++ is the ultimate example of a design by committee language. And that committee is huge.

      Huge indeed, but judging by the results, not particularly good.

      A doc that needs to be read by more people is the C++ Frequently Questioned Answers [yosefk.com].

      • A doc that needs to be ignored is the FQA. The author seems to have some sort of thing about denigrating C++, and either doesn't know what he's talking about or lies a lot.

        I went through one random section carefully. (If necessary, I can go through another one carefully and report.) It's bad.

  • by SanityInAnarchy ( 655584 ) <ninja@slaphack.com> on Tuesday June 21, 2011 @08:48AM (#36511924) Journal

    It's been awhile since I've had to do any C++, so maybe I'm just missing something, but it seems like either there's a lot of retarded functionality here, or there's a lot of TFA which introduces a feature, even motivates it, but doesn't actually explain what the new version looks like. For example, with "Rvalue References":

    void naiveswap(string &a, string & b)
    {
    string temp = a;
    a=b;
    b=temp;
    }
    This is expensive. Copying a string entails the allocation of raw memory and copying the characters from the source to the target...

    Ok, first, what? I thought standard library string implementations were supposed to be efficient, and include some sort of copy-on-write semantics, which would (I would hope) make the above a shuffle-pointer-around instruction instead of a copy-data-around instruction.

    Second, here's the newer, better syntax:

    void moveswapstr(string& empty, string & filled)
    {
    //pseudo code, but you get the idea
    size_t sz=empty.size();
    const char *p= empty.data();
    //move filled's resources to empty
    empty.setsize(filled.size());
    empty.setdata(filled.data());
    //filled becomes empty
    filled.setsize(sz);
    filled.setdata(p);
    }

    Regarding the first comment, no, I really don't, unless the point is that this is what the code for "moving" would look like if implemented in older versions of C++. But also:

    If you&rsquo;re implementing a class that supports moving, you can declare a move constructor and a move assignment operator like this:
    class Movable
    {
    Movable (Movable&&); //move constructor
    Movable&& operator=(Movable&&); //move assignment operator
    };

    Ok, cool... But where is this used in the "moveswapstr" example? Does this make the "naiveswap" example automagically faster? Or is there some other syntax? It doesn't really say:

    The C++11 Standard Library uses move semantics extensively. Many algorithms and containers are now move-optimized.

    ...right... Still, unless I actually know what this means, it's useless.

    It looks like there's a lot of good stuff here, and the article is decently organized, but the actual writing leaves me balanced between "Did I miss something?" like the above, and enough confusion that I'm actually confident the author screwed up. For example:

    In C++03, you must specify the type of an object when you declare it. Yet in many cases, an object&rsquo;s declaration includes an initializer. C++11 takes advantage of this, letting you declare objects without specifying their types:
    auto x=0; //x has type int because 0 is int
    auto c='a'; //char
    auto d=0.5; //double
    auto national_debt=14400000000000LL;//long long

    Great! Awesome! Of course, this arguably should've been there to begin with, and the 'auto' in front of these variables is still annoying, coming from dynamically-typed languages. But hey, maybe I can write this:

    for (auto i = list.begin(); i != list.end(); ++i) ...

    Instead of:

    for (std::list<shared_ptr<whatever> >::iterator i = list.begin(); i != list.end(); ++i) ...

    It's almost like C++ wanted to deliberately discourage abstraction by making it as obnoxious as possible to use constructs like the above. Anyway, that's what I expected the article to say, but instead, it says this:

    Instead, you can declare the iterator like this:
    void fucn(const vector<int> &vi)
    {
    vector<int>::const_iterator ci=vi.begin();
    }

    • by siride ( 974284 )

      The article messed up in a number of places as you surmise. You can use auto in for-loops. I don't know why the example didn't show that properly (I was scratching my head).

      As for the swap example, what ends up happening is that with move semantics, you can go back to using the naive version, but it will actually be efficient because under the hood, it uses the rvalue references instead of copying. It will behave is if it were written using all that "pseudo-code" (don't know why he called actual code "ps

    • Ok, first, what? I thought standard library string implementations were supposed to be efficient, and include some sort of copy-on-write semantics, which would (I would hope) make the above a shuffle-pointer-around instruction instead of a copy-data-around instruction.

      The string implementation is just an example. The current problem is that it is difficult to implement move semantics without having a special case for every class. The introduction of rvalue references enables a class to implement both copy and move semantics in a way that lets other classes transparently move the objects around. The move semantics are that the content is copied but the original need not be preserved (since often the original is a temporary). It enables other code (template libraries for c

    • Second, here's the newer, better syntax:

      void moveswapstr(string& empty, string & filled)
      { //pseudo code, but you get the idea

      size_t sz=empty.size();

      const char *p= empty.data(); //move filled's resources to empty

      empty.setsize(filled.size());

      empty.setdata(filled.data()); //filled becomes empty

      filled.setsize(sz);

      filled.setdata(p);
      }

      Regarding the first comment, no, I really don't, unless the point is that this is what the code for "moving" would look like if implemented in older versions of C++.

      Yes, that is what the code looks like without move constructors. That has nothing to do with C++11, and yes, it's really ugly.
      This that follows is the declaration (not implementation) of a move constructor.

      If you&rsquo;re implementing a class that supports moving, you can declare a move constructor and a move assignment operator like this:
      class Movable
      {
      Movable (Movable&&); //move constructor
      Movable&& operator=(Movable&&); //move assignment operator
      };

      Ok, cool... But where is this used in the "moveswapstr" example? Does this make the "naiveswap" example automagically faster? Or is there some other syntax? It doesn't really say:

      Now you can do
      Movable foo = bar();
      and it'll call the move constructor rather than the copy constructor when constructing foo. The advantage is important. For example, in the case of a string or a vector you don't copy the contents with the copy constructor just to delete the original when the rvalue goes

  • Do not read this article, it makes C++0x look bad by giving terrible examples of the new features. Even features I've been excited about look stupid after reading this. The article shows how *not* to use a lambda expression. A regular for loop would be better here. Using "auto" on int and long does work, but defeats the purpose. The second example of auto doesn't even make sense since it doesn't actually include the word auto. It should be something more like: auto ci=vi.begin();

    Just ignore this and g

  • by ifrag ( 984323 ) on Tuesday June 21, 2011 @09:19AM (#36512400)

    What is the big fuss about getting a garbage collector anyway? Why does it even matter? Good C++ code shouldn't need a garbage collector. If memory was allocated within an object then the destructor should be taking care of it. And with shard_ptr (which people should start using) it's taken care of within there anyway. Is this wanted so everyone can start coding sloppy C++ and forget about the delete calls? I suppose for those using some 3rd party library that behaves poorly and is totally out of your control it could be nice to stop that from leaking all over. Still, it should have been done right in the first place.

    I suppose there might be some argument for preventing excessive memory fragmentation. Is there some other benefit to having one?

  • ...if I'm not a C++ programmer today?

    I stated as a C programmer in the 1980s. I've used three different object-oriented extensions to C, and C++ was neither the first nor the best of them. I'm not in an industry (like video gaming) that pushes me toward C++ with any pressure at all. Every few years I take a look at C++ and conclude that it's safe for me to continue ignoring it.

    Is there anything different this time around that would change this, that's easy to explain to someone who's not already a C++ pr

  • ...in 1995 when I saw there was nothing of interest in it. If I want to do system level stuff, I'll use C. If I want to do object programming, I'll use Java and/or Go. I don't see the need for a language that mixes both except as a confusing and hard to maintain broth. Do you pass your food through a mixer before you eat it ?

Trap full -- please empty.

Working...