Stroustrup Reveals What's New In C++ 11 305
snydeq writes "Bjarne Stroustrup discusses the latest version of C++, which, although not a major overhaul, offers many small upgrades to appeal to different areas of development. From the interview: 'I like the way move semantics will simplify the way we return large data structures from functions and improve the performance of standard-library types, such as string and vector. People in high-performance areas will appreciate the massive increase in the power of constant expressions (constexpr). Users of the standard library (and some GUI libraries) will probably find lambda expressions the most prominent feature. Everybody will use smaller new features, such as auto (deduce a variable's type from its initializer) and the range-for loop, to simplify code.'"
"Not a major overhaul"? (Score:5, Insightful)
I mean, it's not, but it makes it sound like C++11 is a minor update. Lambdas, auto, concurrency, are these minor updates? There's a lot of interesting stuff in C++11!
Re: (Score:2)
Re:"Not a major overhaul"? (Score:5, Interesting)
I've been using the C++11 for 6 months now in my own project (libbitcoin [libbitcoin.org]) and the new features and syntax really make your code sharper, clearer and better. C++ is no longer that unsafe language if you know how to code in it properly - you never really have to do any manual memory management if you use shared pointers.
constexpr allowed me to create compile time constants that are the function of a bunch of complicated expressions. Sure, I could just put the result in the code, but by using constexpr (a far more expressive metaprogramming utility than templates) I can document where those constants came from by using code. Neat huh!
Using variadic templates, I was able to write decorators that can be applied to any function. I simply wrap my functions with this class and then its operator() will be called before calling the passed in function object (which I can define using lambdas or std::bind now :)
auto means I no longer have to type std::vector>::iterator in every for loop. Likewise for (const transaction& tx: block.transactions) is much more terse and clearer.
The new features to the standard library are brilliant. Threading has never been easier: std::thread t(foo, x, y); will call foo(x, y) in a new thread. When I decide to finish the threads and then join them I call: t.join(); ... Simple.
As libbitcoin is highly asynchronous, I don't like to use exceptions (which thread does it originate in? where does it get caught? .etc). C++11 now provides the header which defines std::error_code(). An error_code object can be tested as a boolean (to see whether the error is set or not) or compared against an enum value (which you define). They also have an error message (which if you defined the enum value it is set to, you can also set the message), and also you can group different error code values into broader categories! Really useful for asynchronous programming.
std::atomic for a thread-safe counter (useful when you have multiple thread paths executing and want to see when they all finished - increment your counter by one after each path completes) and std::atomic for a thread-safe flag. ... That's off the top of my head. There are dozens of many small things like this. C++ was always my 'native' language, but now it's truly my home.
Re: (Score:2)
damn my angle brackets got blanked out.
[system_error] for std::error_code
std::atomic[size_t] for thread-safe counter
std::atomic[bool] for thread-safe flag
Re: (Score:2)
Re:"Not a major overhaul"? (Score:5, Informative)
> What C++ compiler are you using?
g++ 4.6 - standard in Ubuntu
Two of the features I'm waiting on are class level non-static initialisers and templated typedefs. I've heard Microsof's C++ compiler has better C++11 support but I've never tried it.
Beware that MingW has a bug so std::thread is disabled. I've heard mingw-w64 works better. You might want to also try boost::thread (same library essentially, except std::thread has move semantics).
Re: (Score:2)
Re: (Score:3)
VC++ 2010 used to have better C++11 support than g++ for some time, but the latter has overtaken it now, and it looks like it'll keep ahead for the next release also - VC still doesn't do variadic templates, for example. It doesn't have instance field initializers, either, nor templated typedefs.
That said, C++11 support is being implemented pretty rapidly in general - I mean, we've only just got the final spec out, what, a couple months ago? and more than half of it is already supported in all major compile
Re: (Score:2)
Microsoft's C++11 support in VS2010 was pretty good at the time: lambdas, auto, new function decl syntax, and that's about it.
They've really dropped the ball in VS11 though: They've basically added strongly types enums, and that's about it.
Still no word on variadic templates, template aliases or initializer lists.
Re: (Score:3)
Slide 5 of the deck here [msdn.com] says that initializer lists, template aliases, variadic templates, and other features are coming in a series of out of band releases after VC11 RTM (but sooner than the next major release [msdn.com] of VC). That slide also lists the stdlib and language features that are included in VC11 Beta/RTM.
Re: (Score:3, Informative)
Sure. But it should be noted that this feature (along with many others brought to the new stand, I'm sure) were introduced in the Boost set of libraries first.
Re: (Score:2)
That is incorrect.
Re:"Not a major overhaul"? (Score:5, Informative)
You didn't anyway. You type in "int" to loop over a vector.
Only if you want to tie yourself to using a vector. Using a proper iterator costs you nothing in code space or execution time (because for a vector it optimizes down to just pointer arithmetic anyway), but means that at some future time you can replace that vector with a different data structure without having to modify the code that operates on it.
Re: (Score:2, Informative)
for (auto i : v) {
}
Even in terms of typing time it's a nice addition, ignoring the structure-independence benefits of this sort of thing.
Re: (Score:2, Informative)
It pretty simple why you would use iterators.
While the data you store might not change much over time, the amount of data stored for successful apps tends to grow alarmingly over time. Allowing the vector to change to some other more elegant solution when the need arises without having to rewrite large swaths of code.
Re: (Score:2)
For a vector both are equivalent, but for structures like "list", iterator is faster.
Re:"Not a major overhaul"? (Score:5, Insightful)
Take goto, which is all that's really needed for modern programming. Using goto, you can implement subroutines (gosub like functions), while and for loops, etc. But each time you implement one of the higher constructs, your implementation will be slightly different. And if you force yourself to use the optimal implementation all the time, you'll just be writing a lot of boiler plate code. So having functions and while loops implemented as language constructs is a good thing. Similarly, std::thread + lambdas is a great addition.
goto is all you need for modern programming? (Score:3)
(Not arguing with your broad point that these new addirions to C++ will be useful.)
Goto is no way sufficient for modern programming. You also need some way to manipulate whatever passes for the (effectively stack) constructs that allow nested parameters and locals. And you need some way to hide the bulky extra code (as in text macros and such).
I got bit on this when I should have known better, back in '97 or so -- using a Fujitsu CoBOL, forgot that the old CoBOL PERFORM was kind of like the old BASIC GOSUB.
Re:"Not a major overhaul"? (Score:5, Informative)
Don't forget initializer lists, variadic templates, non-static data member initializers, finally fixing that Template> (note the >>) thing, rvalues, nullptr, strongly-typed enums, constructor improvements (holy god we don't have to rewrite every fucking thing every fucking time or split off into an ::init()), user-defined literals which is crazy cool combined with templates and initializer lists, and lots of stuff I'm sure I'm forgetting about.
Since starting on C#, I've kind of felt like I'm back in the dark ages in C++, even as it remains my favorite language. I've already started using a lot of these improvements, and while C++ still has it's rough edges, the improvement in "fun" while coding is massive. No more for (some_container_type<vector<map<int, string> > >::reverse_iterator aargh = instance.begin(); aargh != instance.end(); ++aargh) for me!
Re: (Score:2)
Heh, thanks for filling in the rest. I knew there were more, but I was just throwing down what I could remember off the top of my head. I was watching Bjarne talk about C++11 at Going Native and now I'm anxiously awaiting our (long overdue) transition to VS2010 (from 2005). I know it doesn't cover all the good stuff, but it has a lot of the goodness in there. Though, I'm writing cross platform code with a Mac team that refuses to use Clang, so God knows when I'll be allowed to use anything from C++11 :(
Re: (Score:2)
Re: (Score:3)
firstly, I wish I was using VC6 still - the IDE was the best there ever was, fast, simple, didn't flicker or use up all your RAM.
However, you can use a different IDE [wordpress.com] if you must keep the old compiler for backwards compatibility.
Alternatively, you can replace the compiler [intel.com] in the IDE.
Re: (Score:2)
Wait, there is an object oriented version of C?
Theses are days of miracle and wonder.
Re:In practice it's like a different language. (Score:5, Insightful)
Re:In practice it's like a different language. (Score:5, Interesting)
Now be careful, because inheritance was not really intended for code reuse. If it does help with code reuse, that's a positive consequence, but it's not what inheritance is for, first and foremost. See Liskov substitution principle and all that jazz.
Re: (Score:2)
class A
{
public:
enum Type
{
TYPE_A, TYPE_B, TYPE_C
} mType;
void Foo ();
};
class B : public A
{
void Foo ();
};
class C : public A
{
void Foo ();
};
A * p
Re: (Score:2)
The practices you have listed are actually good C++ programming (except "custom string and array classes", whatever that means). Just because there is a bad library bundled with the language, it does not mean that everyone must prefer it over the native libc, it is useful only when it fits the purpose of the program.
Re:In practice it's like a different language. (Score:5, Insightful)
>Time to join the 21st century grandpa. FILE* leaks.
Hell no. And get off my lawn.
printf() isn't typesafe, but it's a fuckton more readable than all that cout formatting stuff. Also, the fact that it's not typesafe isn't really an issue if you don't suck - trivial unit testing will pretty much show any problems immediately. Besides, gcc/g++ is nice enough to warn you about egregious ones now.
FILE* leaks? I assume by this you mean when sloppy programmers fail to close their files and you start burning through file descriptors. Sounds like a bug to me, and again, stop sucking. Or do what we do - throw an object with a destructor containing fclose() around it. Then you get all the awesomeness of of FILE* (including those awesome formatting commands like fprintf and fscanf) without the danger of your file staying open when something goes nuts.
Why on earth would you want memcpy() to call anything? It's a low level byte move. Anybody with five minutes of familiarity with it should know that. If you wanted something different, use the assignment operator.
void* have all sorts of applications, most recently to me in writing architecture neutral VMs where really all the native machine knows is that it's moving around some sort of pointer.
Now the custom string and array classes? That I'll agree on. Troll on.
Re:In practice it's like a different language. (Score:5, Insightful)
printf() isn't typesafe, but it's a fuckton more readable than all that cout formatting stuff
Readable? Meh. Localisable? Now that is an important attribute. Consider this trivial bit of code:
You want to localise this, so you wrap each string in a function that returns the localised version (by the way, gcc and clang have an attribute that you can put on functions that says if the output is safe to use as a format string in any case where the input is). So now you have something that looks like this:
Okay, no problem. Now let's consider the C++ equivalent:
Harder to read? Maybe, but the tokens are all in the order that they'll appear in the output, so I'll give C++ that one. Now let's localise it. How about something like:
That's fine, right? No more complex than the C version. Well, almost. Let's make French the target language. We want to turn 'the black cat' into French. Now we have a problem. In French, the word order is different. The result we want has the colour after the noun. No problem in the C version, the format string is just translated as "Le %2$s %1$s". The arguments are reversed (well, it's a little more complex because you also need agreement between the noun and the article, but I'll skip over that for now - it can be solved in the same way). What about the C++ version? Well, because the word order is in the code, not the data, you need different code paths for English and French. And that's just with a three-word sentence. Now consider the kind of sentence that actually appears in a typical UI. Consider German word-order rules. Your simple C / Objective-C strings file has to be replaced by a huge tangle of C++ code.
Re:In practice it's like a different language. (Score:4, Funny)
That's fine, right? No more complex than the C version. Well, almost. Let's make French the target language. We want to turn 'the black cat' into French. Now we have a problem. In French, the word order is different. The result we want has the colour after the noun.
It seems like it would be a lot easier to just change the word order of the offending languages than to screw up perfectly good C++.
Re:In practice it's like a different language. (Score:4, Informative)
Re:Uh. No. (Score:4, Informative)
Operator overloading is to address the ambiguity of having by-value and by-reference passing of objects being possible via different semantics in the language.
If I have a pointer and write:
ObjType* pObjRef =
then it's pretty obvious I have an object reference.
But but what does
ObjType Obj2 = Obj1;
actually mean?
C++ defines this type of transaction as always being a copy operation. But an object is a complex datatype - doing a straight copy of all it's memory doesn't necessarily give me sensible behavior. So you need operator overloading to let you enforce sensible behavior.
That you can also use it to create syntactic sugar or completely illogical behavior doesn't make it bad though. And absent a garbage collector, I'm not sure it actually makes sense to do what C# does and try and treat all object variables as references (in that when would you deallocate things?)
Re: (Score:2)
I still prefer printf to cout. Though php's echo is better than both, which is sad.
Re:In practice it's like a different language. (Score:5, Insightful)
Don't be a zealot, pragmatic programmer should find the right trade-off between reusing code and writing an optimal one for a specific problem/area. Nothing can be optimal in all cases - sometimes you need to be as close to hardware as possible [beyond3d.com] at the expense of unreadable/inflexible code (for me, those are the most interesting and challenging areas), and sometimes you only care about maintainability of your code by a disposable programming drone.
Re: (Score:3)
So what?
I think he simply claimed that you have to deal with C++ written by C programmers all too often. That's my experience, too.
STL isn't suited for all possible uses, sometimes you need [open-std.org] your own string and container classes.
I don't see what that has to do with the above. I suppose there are some rare cases where the standard library isn't appropriate, but are you arguing this is an excuse *never* to use it?
By the way, your reference seems severely dated. Some of its complaints are still valid, but seem based on the state of STL support ten years ago.
Re:In practice it's like a different language. (Score:4, Informative)
I think he simply claimed that you have to deal with C++ written by C programmers all too often. That's my experience, too.
I'm probably one of those C programmers. I use C++ features when I feel they are appropriate, but my definition of "the right thing" changed over years. I started to value custom-tailored solutions, often hardware- and problem-specific. No longer I'm trying to find (or create) code that would fit all (or even the most) cases, and micro-managed security is of lesser concern to me.
I don't see what that has to do with the above. I suppose there are some rare cases where the standard library isn't appropriate, but are you arguing this is an excuse *never* to use it?
There are always multiple tradeoffs involved, that's why I am very wary of saying "never". STL is no silver bullet, this is what I'm saying.
E.g. STL is bad at managing memory, it's hard to make it NOT allocate it dynamically - yes, you can write a custom allocator for it, but STL allocators are inflexible and also - for some poorly thought reason - manage object construction, not just memory allocation, making this unnecessarily hard. STL is a template library, and templates produce separate implementation for every type used - whereas you can have a single void *-based container for all your POD types, with templates providing just minimal wrapper. Also, STL makes it hard for you to control how often memory (object instances) is copied - there's no way to influence its behavior if memory copying tops your profiler results.
If you are developing primarily for desktop computers which are quite beefy (and also vague in terms of hardware), this may matter less (although it will never cease to matter - just think of all that slow code running on our desktops which eats the performance improvements we still (marginally) get, making desktop performance appear flat since 2004), but if your target is well-defined hardware-wise and if you know/set "upper bounds" for all the practical problem sizes your program is designed to handle, you can think of more optimal solutions for your case. This is one of reasons why you can still play the newest games on 2005 hardware (XBox 360) which hasn't even got an out-of-order CPU, while running the newest desktop software (not games!) on PC of the same era is problematic.
To sum up, I'm not saying "never use STL", but I would not say "always use STL" either. People claim that using "standard" code helps you create more secure, robust, performant programs - but in my experience, you will end up running a lot of custom tools (all kinds of profilers and validators) anyway before shipping your binary, that makes the point of "performant/secure code by design" moot. When profiler tells you that some code in an STL container underperforms, reimplementing it - or even understanding why that happens - is harder than fixing/improving your own implementation, yet you'll probably have to do that anyway. And no one starts "from scratch" these days, each "low-level" programmer I know has their own set of STL-alike classes.
By the way, your reference seems severely dated. Some of its complaints are still valid, but seem based on the state of STL support ten years ago.
Well, it is perhaps improving with new "move" constructors and whatnot, but that's actually a problem: it's better to have cross-platform code with predictable behavior than code that is supposedly optimal everywhere, but which depends on highly varied implementations. What good is it for me to know that some compilers (e.g. gcc), on some platforms (e.g. x86), handle new, C++11-ready STL well - gcc isn't particularly good at optimizing code even for x86, and another compiler that is a good optimizer may not support the newest features and make my STL-heavy code suck.
P.S. Also, STL (in implementations I saw) is written in quite unreadable, convoluted style - I always wondered why. This is of course less rele
Re: (Score:3, Insightful)
#warning rant coming
"printf instead of std::cout"
I love c++, but it definitely has some dark spots, even still the long overdue c++0x update (c++11 whatever). Thank deity we finally have standard smart pointers, better templates in various ways, move semantics, etc. It was really necessary to finally have that, even if it was a decade late (I'm sure we lost quite a bunch of good c++ programmers and projects to more newfangled languages in the delay). Even though we often won't be able to use it until all co
Re: (Score:3)
Maybe because pure C++ with all its advances looks worse than random perl code or assembly.
Im not asking for cobol like scheme, but come on, enough of the !@#$%^&*(){}|} magic
I want auto! (Score:2)
Unfortunately I code in java these days.. chances that oracle will see the light? :-)
Re:I want auto! (Score:5, Funny)
chances that oracle will see the light? :-)
Last time they saw the Sun, it did not end well...
Re: (Score:2)
chances that oracle will see the light?
Roughly the same as the chance that Larry Ellison will fly his MiG 25 straight into the side of a mountain.
Re: (Score:3)
Re:I want auto! (Score:4, Insightful)
Now what happens when you change the name of a return type from a commonly used function? Have fun with your maintenance nightmare. If you are lucky the compiler will complain, if you are unlucky you break existing code without knowing it.
Re: (Score:2)
Re: (Score:3)
Re: (Score:2)
Re: (Score:2)
However, take a look at clang [llvm.org]. One day, this and much more will be possible.
Re:I want auto! (Score:5, Insightful)
Prohibiting use of "var" is gross over-kill.
There are times where it's use is not recommended, certainly. But even in those cases, it can lead you to the point that there's a "bad code smell" where methods aren't named well, variables aren't named well, classes aren't named well.
var x = foo(); is definitely less readable.
But var x = new ComplexObject(); is every bit as readable, if not more so, because you don't have a redundant "ComplexObject" in the declaration. You always know exactly what type "x" is. It's also very useful in cases where the return type is a complicated generic. it saves a lot of typing, and is definitely more readable.
Here is a very good discussion on the benefits and uses of "var":
http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html [blogspot.com]
Re: (Score:2)
Re: (Score:3)
Prohibiting use of "var" is gross over-kill.
Gross overkill is, of course, the main point of most coding standards.
Re: (Score:3)
In general I agree.. but for some stuff (iterating through a collection for instance) I think it is acceptable. When you start dealing with collections of collections, iterator types become a nightmare!
in Java of course you can just use the foreach syntax (Kitten kitten : kittens).
Re: (Score:3)
in Java of course you can just use the foreach syntax (Kitten kitten : kittens).
Which is also a C++11 feature, now. Except they call it a "range-based for loop."
for ( Kitten& kitten : kittens )
Using a reference is optional, I think, but is probably the better way to go in the general case (so you can modify the object instead of a copy).
Re:I want auto! (Score:4, Interesting)
var my_object = new my_class();
v.s.
my_class my_object = new my_class();
Here using var just saves a few key struck (or a lot, in case my_class happens to be a type with a particularly long name). In any case the type of my_object is perfectly known and quite visible so I think using auto is just fine.
There are however cases that a complex type is used while we actually DO NOT care for the type per se. For example in C++ consider the case for a lambda function:
auto my_fun = [](int i) { return i * i; };
Here I actually don't care about the exact type of my_fun. All I care is that it take an int and returns an int which I can see clearly. Finally, another case could be situations in template programming where insanely complex types are used/generated and we don't want to (or even cannot) type them again and again. Also I guess in Java or C# you might get away by cheating and using an object (I hate it when people do that!) but we don't have that luxury in C++.
Re: (Score:3)
(object) ~= (void*)
I mean that in spirit, not in actual details. Yes, I know there's about a billion, trillion ways they're different.
Re: (Score:2)
Seriously get a better IDE if you think using var is confusing.
var saves me from having to do this:
Dictionary, AnotherClass myCollection = new Dictionary, AnotherClass();
instead I can go:
var myCollection = new Dictionary, AnotherClass();
which is significantly more readable and removes redundant overhead of typing a type twice. And if you can't figure out what type it is, you should change your profession.
or even better:
var collection = someclass.ACollection;
without having to explicitly know what type AColl
Re: (Score:2)
Here's a construct that I used today:
If I want to iterate through this, I need to create a variable of type
. Since I'm not totally sure of the exact type of my map, I need to find out where it's declared and copy that. If I then change that vector to a list, I need to change every iterator that uses that. Okay, I should probably use a typedef, but sin
Re: (Score:3)
Auto in K&R was a storage class, not a request for compiler type inference.
Re: (Score:2)
And also completely redundant (every local variable is an auto variable unless declared differently), and thus completely useless and never used.
I think it's wonderful they managed to re-purpose a dead keyword into something wonderfully useful, and the name even fits so well.
Re:I want auto! (Score:5, Informative)
"auto" was always implemented, since the very first version of C, it just had a different meaning - it means that variable has an "automatic storage class" (as opposed to "static storage class" etc). Because automatic was the default, it was almost always redundant, but it did have a meaning.
It actually goes way back to B [wikipedia.org], which only had a single data type - machine word. Variable declarations looked somewhat like C, but, for the lack of type, they started with the storage class instead, i.e.:
In C, we've got types, so you'd normally write "static int y" for a static local, and just "int z" for an automatic one - "auto" being implied. However, C inherited some of B's semantics as "default int" - i.e. if the declaration is clearly a variable, but it omits the type, assume that type to be "int" (i.e. machine word). So in C the above code snippet from B is actually valid, and declares x, y and z to all be ints.
Then "auto" got inherited by C++, which dropped the "default int", making auto completely redundant - you couldn't write "auto x" in C++ anymore, and in all other cases where you could use "auto", like "auto int x = 123", it was always redundant. So when they appropriated it for type inference in C++11, it was technically a breaking change - it just wasn't ever used by anyone in production code in the old way, so nobody noticed.
Re: (Score:2)
Then simply prepend the type identifier to the variable name, simples!
Or, if you don't do this, you can use the IDE's ability to tell you the type by hovering over the variable. In which case, it really doesn't matter if you declare it using var or not.,
Re:I want auto! (Score:5, Insightful)
Because var still works within the type system and gives you compile-time errors, and casting to object is a massive sledgehammer that delays errors until runtime (with all of runtime error checking's glory, like only failing some of the time, which you can basically read as "never on a developer's machine, sometimes on TQA's machine, and always on a customer's machine (unless support is on the phone with them)"), and a stupid idea in general (I'm looking at you, Objective-C!).
Re: (Score:2)
It gives you some of the benefits of duck typing with very few of its drawbacks, and the reduced noise makes your code clearer. I know that seems counter-intuitive to you right now, but if you try it, you'll see the benefits, and realize that the type names appearing next to the declarations is, in most cases, redundant or irrelevant when it comes to actually understanding what the code does.
It's more of a fuzzy thing, but I started using it at my job, everybody hated it for two weeks, I gave no fucks and k
Re: (Score:2)
if its just the same function, build the properties for the anonymous type before initializing the anonymous type.
Can you explain what you mean by this?
You can't pass an anonymous type to another function as its type
Actually, you can, if that function is generic. It's why you can pass an IEnumerable of anon type objects to something like .Where(), and access properties on that object without any casting within the lambda that you also pass.
Nothing to see (Score:2)
Seriously, a big disappointment.
and in the next revision... (Score:5, Funny)
Comment removed (Score:3)
Not seeing (1) (Score:5, Insightful)
I don't think you'll see a lot of people flaming C++, there just aren't that many people that care one way or the other anymore.
I think some of the new features look nice but mainstream use has been shifting away from C++ for a while and I'm not sure I see these new features drawing many back...
Re:Not seeing (1) (Score:5, Interesting)
Mainstream use is shifting back to C++ since Microsoft decided that C++ was batter than C# (or at least Sinofsky and the Windows team decided that was the case). Herb Sutter has done a lot of presentations on the new paradigm at Microsoft - do a quick google.
Of particular note is the reason they're giving for this: in the datacentre native code reduces the amount of energy required to run your apps, and that adds up significantly if you're using dynamic or even JIT language.
Re: (Score:2, Funny)
That's way to verbose. I overloaded the ;
Re: (Score:2)
C++ SUCKS!! It's a piece of shit language with a very crappy garbage collector
If you are making extensive use of the C++ garbage collector and it isn't working very well, I can understand your frustration :D
Re: (Score:2)
Re: (Score:3)
Garbage collectors only manage memory. Smart pointers, on the other hand, can manage any kind of resource - whatever you release in your destructor.
That's why languages like Java and C# still need stuff like Closeable and IDisposable, and syntactic sugar for them to avoid writing try/finally ladders. Whereas in C++, resource management has always been done right, and memory is treated as just another kind of resource.
Re:For my next trick (Score:4, Interesting)
In one corner we have memory, which is 99% of the "resources" needed to be managed
Go ahead, count the number of calls to "Close" and "Dispose" in a real world C# or Java app. Then get back to us with some solid number for that 99% claim.
Simple example, open a file, write to it, let the dtor flush and close. If flushing fails, you won't know, because dtors can't return anything, and exceptions in dtors is a big no-no (because, incidentally, there's no GC to free the stuff). That's _wrong_.
Suppose you're right, and you detect that flush failed during close. What are you going to do?
Suppose furthermore that you have an exception in flight, and you've just had flush fail in your finally-block (assuming C#/Java). What are you going to do now?
If you want exception safety, you need RAII, period. If you have RAII, you might as well use it for memory.
Smart pointers are a lousy GC scheme that does memory badly (ref counting is inefficient, especially on MP systems, and cannot handle cycles)
Those claims that refcounting is inefficient are old, but somehow they only show up in synthetic tests. In real world apps, something written in C++ is invariably faster and more responsive than alternatives written in managed languages. That's precisely why C++ is still used far more widely for desktop apps, and is used almost exclusively anywhere perf really matters (like games).
And there's weak_ptr for cycles.
Re:For my next trick (Score:4, Interesting)
Oh, and before you mention weak references (to be totally honest, I am not even sure if there is a standard weak reference in C++)
std::weak_ptr in C++11. Been there for 7 years now (originally as std::tr1::weak_ptr), and for a few years before that in Boost.
I'll mention that very few C++ programmers know what they are.
That's the problem with those programmers, not the language. C++ is powerful and fast by design; that, unfortunately, also makes it complex by design. It's not a language for everyone, and Java and C# certainly have their very large niche. But C++ is a very powerful tool when used right.
The syntax of C++ is so crowded that the language is only used for low level stuff where the extra 5% performance boost is a big deal.
That's emphatically not true. I've repeated it several times already in this thread, and I'll repeat it again: most desktop software today is written in C++. Heck, even a fair bit of OS X software is written mostly in C++, especially if you look at the size of it (MS Office, Photoshop). The reason for that is that perf boost (relative to Java/C#) is more like 20% for common tasks; but, more importantly, there is a marked responsiveness improvement due to lack of GC. And responsiveness is some really subtle stuff - it's not quite the same as "fast", but it's very sensitive to stutter on the order of tens of ms (a delay over 100ms is already noticeable by the user).
You can write good UI software in managed languages, but then you need libraries that are themselves written in native code, at least rendering and input layer. Otherwise you end up with a clumsy pig like Swing.
Re: (Score:3)
I'll mention that very few C++ programmers know what they are.
That's the problem with those programmers, not the language. C++ is powerful and fast by design;
Not really. Most Java programmers know about the weak references in Java. And in Java they are less necessary than they are in C++ (because the C++ gc model steaming from smart pointers is based on reference counts). If a necessary tool goes underused in a certain context, then it is the problem with how the context is presented to its audience -- not with the audience.
But C++ is a very powerful tool when used right.
Any tool is only as powerful as it is useful. It is not reasonable to judge tools only by the peak performance achieved by its most commi
Fascinating Software Engineering Challenge (Score:5, Insightful)
In some ways, a lot of what is being added to C++ makes me think of Scala, just less readable.
While the additions and extensions certainly make things more interesting and potentially more powerful/easier for the *individual* programmer, I look forward to seeing what sort of interesting train wrecks happen when larger teams try to make use of these features. I certainly hope the debuggers are being updated to be useful when someone's written a template that uses a #define'd macro to specify a closure that is passed through an anonymous function, etc.
This strikes me as the next generation's 'multi-threading' -- where almost every programmer claims they can handle multi-threaded programming, but very few actually do it well. Particularly in teams when interactions require coordination. Going to take a whole new round of winnowing the wheat from the chaff when it comes to finding developers who can actually use these features well without driving their coworkers insane.
Re: (Score:3)
Time to overhaul the academics. Nearly every engineering course here (I'm in India) has a couple of programming courses. A lot of students do coding some time or the other. Yet not even a sentence is uttered about threads or parallelism, even though practically every computer they code in has multiple cores. They should probably introduce a course on parallel processing as an elective for freshmen.
Re: (Score:3)
Re: (Score:3)
Both C++ and Scala are attempts to modernize limited, poorly designed languages (C, Java) by adding things like type parameters and functional features. There are a bunch more of those attempts and I think they have mostly been failures. It's roughly like: "Never try to teach a pig to sing. It wastes time and annoys the pig"
He's optimistic (Score:2)
FTA
I expect to see the first complete C++11 compiler sometime after I see the apocalypse.
Oh right... I guess that would be December 2012, wouldn't it? :)
Seriously... while a lot of compilers implement some of the features, I really don't think there's a hope in hell of seeing any real progression to adopting the standard. With C, the standard developed around what many compilers were already doing... ditto with the original C++ spec.
Re: (Score:3)
The majority of it is implemented. http://gcc.gnu.org/projects/cxx0x.html [gnu.org]
Re:He's optimistic (Score:5, Informative)
> But C++11 describes a standard that absolutely nobody has ever got anywhere close to, so I don't imagine that there's going to be a lot of drive to adopt it.
All popular C++ compilers already implement large parts of C++11, so the chance of seeing widespread C++11 adaption in the not so distant future is pretty high. Also this wasn't really any different with C++98, which essentially no compiler supported on release and which then took a few years to gain widespread adoption.
Re: (Score:3)
All popular C++ compilers already implement large parts of C++11, so the chance of seeing widespread C++11 adaption in the not so distant future is pretty high. Also this wasn't really any different with C++98, which essentially no compiler supported on release and which then took a few years to gain widespread adoption.
C++98 was worse. There was extern templates, which was a major mistake (read the proposal to remove it from C++11 for some amusement). There was Microsoft, who lost interest in C++ around that time, and condemned a generation of Windows programmers to Visual Studio 6 and a weak standard library implementation. And yet gcc was usable around 1999 or so. I started using the std namespace in late November that year.
Some idiotic stuff too (Score:4, Interesting)
I guarantee you will quickly come to hate the new "narrowing" errors, for example any time int converts to float inside initializer curlies, or double to float. As a language feature, this lies firmly in the category of wanking.
That said, my code is all full of lambdas now, thankyou. On the other hand, lambda syntax is uglier than sin. While a lambda can do anything a lexically scoped nested function can, it is not pretty. Now obviously, there is no reason not to support proper lexically scoped nested functions, as GCC already does. Arguing that they are now unnecessary because of lambdas is, again, wanking. The practical fallout is that when you move a lambda-style helper function to global scope or to member status, you have a bunch of editing to do, to remove the ugly auto/lambda bits.
Another big disappointment is, nothing was done to address the good features C99 has that C++ does not. Designated initializers and variable size array parameters, to name two. Wanking again.
On the whole, there is too much wanking going on in the C++ stewardship process. Guys, you need to remember, C++ does not exist only as a means of compiling the STL.
Assigning new values to constants can be useful! (Score:2)
I was amused by the comment "If that incr(0) were allowed either some temporary that nobody ever saw would be incremented or - far worse - the value of 0 would become 1. The latter sounds silly, but there was actually a bug like that in early Fortran compilers that set aside a memory location to hold the value 0. "
Back then, I wrote Fortran subroutines which took computed dimension arrays by declaring the arrays with crazy bounds, numbers I hoped would never be used as constants, and then "assigning" the re
Just awful what C++ is turning into (Score:2)
I watched a few of the "Gone Native" webcasts on the C++ extensions, and it's crazy what they're doing with the language. Are the features useful? Yes, but they're taking a complex language and slapping on yet more functionality. Some new C++ code syntax doesn't even *look* like C++ anymore it's so different. Not everyone is a C++ guru and the language is bad enough supporting so many different paths to the same implementation outcomes. This is just going to make staffing, testing, training, and code r
Re: (Score:3)
They need to just start from scratch and create a limited subset of features that doesn't pretend to be C and doesn't lug around all of the past mistakes in the standard, and call it C+++.
They did. Check out the D Programming Language.
So, has it gained a standard ABI yet? (Score:2)
Probably the last thing preventing it from being truly safe and useful in shared libraries across implementations.
How many years has it been?
So what is a good book to learn C++11 (Score:2)
Re:So what is a good book to learn C++11 (Score:5, Funny)
Dante's Inferno. Sample quote:
Obscure, profound it was, and nebulous, So that by fixing on its depths my sight - Nothing whatever I discerned therein.
Meh... (Score:3, Interesting)
Good for showing off.. bad for getting actual work done, esp for projects that last more then a year or two.
Re: (Score:3)
I gave up on C++ years ago. It has really become a 'geek cred' language with a constantly changing 'right' way an aesthetic, perfect for figuring out if a fellow geek is from the same snapshot of teaching you came from, but that is about it. It has become overly complex with redundant language features that one needs to keep relearning in order to understand other people's code.. and of course with complexity comes the ability to show off your knowledge through doing things in 'clever' ways. Good for showing off.. bad for getting actual work done, esp for projects that last more then a year or two.
Well, what are the alternatives? I my domain, it's plain old C. Java is not an option, and from the little I hear fashion changes *more* quickly there anyway.
I think your impression of the changing "right" way is warped, or perhaps you're in a subculture I'm not familiar with. I see these different ways:
(a) C with classes, from C programmers who've read a book but don't quite get it.
(b) OOP/Design Patterns rule! Popular in the mid-1990s. Lots of inheritance and stuff; every piece of code aspiring to gen
Re: (Score:3)
Re:News? (Score:5, Funny)
That said, as a professional C++ developer working in HPC, this is exciting.
Stop pretending and get back to your FORTRAN!
Re: (Score:2)
prominent compilers support it? the one supporting the most platforms, gcc, doesn't have it all yet
Re: (Score:3)
which is in the new standard
No it's not. Vendors have always been allowed to tack on GC. None of the big ones do.
Re: (Score:2)
WTF?
Re:George Bjarne Lucas Stroustrup (Score:4, Insightful)
Re: (Score:2, Informative)
It is easy to refute your argument on memory safety and auto with a single line of code:
auto obj = make_shared( arg1, arg2 );
lambda expressions can only be assigned to an auto, because the actual type is compiler defined.
auto some_callable_type = []( float f ){ return f * f; };
Currency isn't supported? What more do you want apart from: threads, mutexes, atomics, thread local storage, concurrency safe memory model, futures, promises, async tasks and thread exception transfer?
Re: (Score:3)
The main purpose of "auto" is to allow for (auto p = arr.begin(); p != arr.end(); p++) {... } without worrying about the type of arr.
No, it's not. The above is written as follows in C++11:
And, of course, you can just as well use the actual element type there instead of auto.