share
Stack OverflowC++ Urban Myths
[+256] [59] community_owned
[2010-02-11 14:48:53]
[ c++ ]
[ http://stackoverflow.com/questions/2245196] [DELETED]

I'm starting to write an article on what I'm calling "C++ Urban Myths" - that is, ideas and conceptions about C++ that are common but have no actual roots in reality. Some that I've come up with so far are:

TR1 is part of standard C++

It is faster to use iterators to access a vector than operator[]

The C++ Standard contains something called the STL

I'm wondering if the SO C++ community can come up with any better ones? Ideally, they should be expressible in a single sentence, and not involve any code.

Edit: I guess I didn't make it clear enough that I was interested in myths believed by C++ developers, not misconceptions held by non-C++users. Oh well...

(23) TR1 is not yet accepted in the standard, because c++0x is not yet finalized, but it will. - Mathieu Pagé
(24) At least that x denotes a hexadecimal digit is now not a myth anymore. - gimpf
(4) Out of curiosity, was TR1 ever rejected? As I understand it, it was never meant to be "accepted" into standard C++ as such. Did they ever have a vote on "should we adopt TR1 into C++"? - jalf
(133) If you dereference the string "bloody mary" three times in a row, she'll come back to life AND KILL YOU!!!! - FrustratedWithFormsDesigner
A bit hair splitting - STL isn't part of the C++ standard but it is a standard part of C++ for any decent programmer - Martin Beckett
(10) @Martin Beckett: Is there ever a conversation about C++ that doesn't involve hair-splitting? ;) - Greg D
(16) @Martin: Not really. The C++ standard library is a standard part of C++ for any decent programmer. Neil's point is that the C++ standard library does not technically speaking contain the STL. It contains a set of class templates and function templates that are copied almost verbatim from the STL library, but it is not the STL library. A few modifications were made when the library was adopted, and many components of the STL were left out. What we have in the standard library is not the STL. It just looks a lot like it ;) - jalf
@Greg ;-) @jalf Not really an 'urban myth' though. - Martin Beckett
(2) @jalf: some of the differences are a pain, though. For instance one came up recently in a question here about std::partial_sum. The STL makes it explicit that the accumulation is done in the value_type of the inputiterator. The C++ standard doesn't make that clear at all (in fact, in the case where a binary operator is given, it specifies an expression which is not how anybody actually implements it). C++0x apparently fixes the C++ standard back to where the STL was. Standards fail. - Steve Jessop
(4) "the library formerly known as STL" - Tom Hawtin - tackline
(3) @tackline: even that's difficult. People who subscribe to the "STL" myth/terminology often think that streams are part of "the STL". But they were never part of the actual STL. So if they're part of "the library formerly know as STL", then so is the whole C++ standard library. But nobody thinks that printf is part of "the STL". The containers/algorithms/iterators/functional parts of the C++ standard library arguably are "formerly known as STL", since the changes are so slight, but they aren't "a library". - Steve Jessop
(2) ...and hanging from the WindowProc function was a bloody hook! - bk1e
(7) The next morning, the kernel woke up in a bathtub full of SoftICE. A DbgPrint had been written on the screen in lipstick: "Pick up the phone and call N-M-I. Your KIRQLs have been raised to HIGH_LEVEL"! - bk1e
(13) I guess SO prefers questions which can be answered and not discussed. - legends2k
(1) I came to this question just to vote to close. I was amazed to see the original poster is Neil. My respect to the author didn't let me do this. I'm still amazed though. Neil, himself, asked a discussion-y question? Is your account hijacked? :) - Mehrdad Afshari
@Mehdrad I didn't intend a discussion - and I've asked several other CW questions. - community_owned
(1) I was kinda surprised as well, but do think it's turned out to be a good question - probably because Neil did a good job of indicating the sort of answers he was looking for right off the bat. If only the inevitable copy-cats would do likewise... stackoverflow.com/questions/2248278/java-urban-myths - Shog9
(1) @Shog9 It hasn't quite worked out the way I hoped. So it goes, I guess. - community_owned
Duplicate: stackoverflow.com/questions/560845/… (but this question is phrased much better, perhaps they could be merged?) - community_owned
(7) I have some suburban C++ myths, and even a couple rural ones. Are they out of scope here? - Ken
(1) We're using namespace urban but if you preface them with rural:: they should be fine. - corsiKa
Why "urban" myths? Are there myths that are not "urban"? Rural myths? - MAK
It is an effective debating technique to label points of disagreement "myths." - JohnMcG
[+247] [2010-02-11 15:13:45] Artyom

There is a language called C/C++.

There is common misconception that if you know C++ you can easily write C code and if you know C that you can easily start writing C++ code.

These languages are so different that I would never put them one near other.


(14) This is one of the things that really irks me. Especially the questions here tagged C and C++. - Yacoby
(9) I used to believe this myth, until I actually spent some time writing C. Hoh boy is it different from writing C++. - Jeff Barger
(50) meh, they do share a common subset, and it is frequently useful to refer to that common subset. it is irksome when c or c++ only features are referred to as c/c++ though - jk.
(34) Effective C++, Volume 1, Item 1: "View C++ as a federation of languages. [...] C: Way down deep, C++ is still based on C. [...] C++, then, isn't a unified language with a single set of rules; it's a federation of four sublanguages, each with its own convetions. Keep these sublanguages [(C, Object-oriented C++, Template C++, The STL)] in mind, and you'll find that C++ is a lot easier to understand." - Jason
(4) The two have enough in common that often (not always) when you ask a question about C, the answer for C++ is either the same, or else the difference can be concisely explained. The answer to the same question in C# or Java is far more likely to be "hmm, really we need to change the question here, the one you asked doesn't directly apply". - Steve Jessop
@Jason: The use of the term "language" in your Effective C++ quote may be inappropriate. Of course C++ is one programming language, defined by its standard. - Daniel Daranas
(102) Trouble is, there is a language C/C++, and it's all over the world. It's not "officially" in existence, but, man, there're millions lines of code written in it. - Dmitry
(30) I write code in C/C++... Usually both C purists and C++ purists dislike my code. - speeder
I (sort of) learnt C++ from Thinking in C++ and started assuming I know C as well. It wasn't until a few days ago I realized what a boob I am in C ! - missingfaktor
(3) @speeder: I don't think purists dislike your code. It's people that understand mixing languages can lead to buggy, unsafe, and messy code. - GMan
(7) This "myth" is true. Almost 100% of C code is compatible with C++ — such code could rightly be called "C/C++" since it is valid and works correctly in both languages, even if it's not perfectly idiomatic in the latter. C and C++ have much more in common than F# and OCaml, yet programmers of those two languages regularly admit that there's a common subset the two languages share. - Chuck
(2) When I was at University, we learned C and then C++. By the time I was done, they were teaching C++ first, in the introductory data structures course. I had the joy of helping many a bewildered student who couldn't get their C code to compile, usually because of something like declaring their variables right before use instead of at the top of the block. If you know C, you can certainly write code that compiles with a C++ compiler. In fact, some C code is so badly written that only a C++ compiler can grok it. That doesn't mean you are writing C++ code, and it's a one way street. - Duncan
(1) I might be wrong, correct me if I'm. Although idealogically they are different, syntactically, you can write efficient C code and compile it using a C++ compiler, can't you say "I've written C++ code"? Techincally, the question isn't if it's following C++ purism, but is it compiled without erros by a C++ compiler which follows the standard. [Note: Am all for purism myself. I am counter-arguing here for the idea's veracity] - legends2k
It is also irksome that even ohloh has been victim to the C++ = C/C++ misconception. - phresnel
@legends2k: The question is generally more about programming style and methodologies, e.g. don't use malloc() until justified. - phresnel
(6) Hmm - my copy of the C++ standard says the following: "C++ is a general purpose programming language based on the C programming language as described in ISO/IEC 9899:1990 Programming languages – C. In addition to the facilities provided by C, C++ provides..." So I think I'd say that insisting that C and C++ are completely different languages is the myth (I think that the Meyers quote that Jason posted in a previous comment is the most useful way to think of this topic). - Michael Burr
(4) The proper name of this language is C+- - Pavel Radzivilovsky
I write C code under C++, using some simple, helpful features of C++ in it. - SF.
The way I refer to "C/C++" is correct. For instance, I will write something like, "the preincrement operator, when applied to pointers in C/C++, do not necessarily increment by 1, but by the size of the pointee." Some people may not use the expression, "C/C++", correctly to describe things that are applicable to both languages, but I do. :-D Regardless of the fact that they're two separate languages, C++ does has a legacy inherited from C and therefore there are many quirks about it that's equally applicable to C. - stinky472
(3) I do not agree. C++ has been designed as a C superset as much as possible, so it is reasonable look at them as tightly related languages. - Lorenzo
(1) I suppose that writing C/C++ programs is better than some of the Fortran/C++ programs I've seen, or VB/C++ programs, or Java/C++ programs, but still, it's best to just write C++ if you are using C++. - Kristopher Johnson
(1) When I write code in C++ or C, I really tend to make sure that I am using pure C or pure C++. If I can do it easily enough in C, I'll write it in C, and all of my files will have the .c and .h extension. When I code in C++, I'll use pure C++, and I'll try doing things in an Object Oriented context (or at least use objects to my advantage). For instance, if I am writing a small application that requires a hash map, I'm much more likely to write this in C++ and use the map class of the STL, then I am to use C and write my own. - Alex Hart
jk: a subset with some subtle differences. For example the order of precedence of the ternary operator ? in C is different form C++ - sergiol
1
[+192] [2010-02-11 15:49:08] Didier Trosset

cout << endl; is the same as cout << "\n";

They are absolutely not! cout << "\n"; simply adds a character to the output stream. cout << endl; does the same but also flushes the stream, which implies a system call, which is terribly slow.

This is IMHO one of the root cause of the C++ iostream reputation to be slow.


(2) IIRC, endl is not required to be "\n". It could be "\r\n" or anything else. It's the local platform's line ending character, and it also has the effect of flushing the buffer as you say. - rmeador
(46) In fact, even when you write cout << "\n", behind the scenes, it will write "\r\n" to the actual file if the platform needs it. This translation is never done if you specify the ios_base::binary flag when opening the file. - Didier Trosset
(39) "cout << "\n"; simply adds a character to the output stream". That's not true. It may also flush the stream, where adding any other character would not, because cout is often line-buffered. It's just not required to flush as endl is. - Steve Jessop
(11) Alas, iostream is also slow because of unavoidable failure checks, locales, and the lack of a guarantee that you can expand the buffer size. Learning it is also harder in my experience than reimplementing my own buffer. - Potatoswatter
@rmeador: endl is required to behave exactly as if it did: stream.put(stream.widen('\n')); stream.flush(); (C++03, 27.6.2.7/1). The use of widen handles non-char streams. - community_owned
(17) I just ran a little experiment. On my machine, printing 10 million times '\n' to /dev/null takes 0.57 seconds; printing 10 million times std::endl to /dev/null takes 1.48 seconds. - Thomas
(20) cout << '\n' will be probably be faster than cout << "\n" :-) - Matt Curtis
(3) And here's a good example of why I don't miss using C++. - Warren P
(3) @Thomas, Matt: I extended this a bit pastebin.ca/1948422. Called with ./test>/dev/null. cout<<endl 8.47s cout<<'\n' 0.96 cout<<"\n" 0.96 fprintf(stdout, "\n") 0.25s. - Manuel
2
[+178] [2010-02-11 14:53:03] Péter Török

C++ is slower than C.


(10) I can't upvote this enough. Yes, C++ can be slower than C, but a competent programmer can write C++ code as fast as C code. - Mathieu Pagé
(1) True, but it might be hard to justify in a single sentence, so it ends up appearing very subjective. - jalf
(1) (+1) Though It takes a LOT of time to get to the stage that a programmer understands (exactly) what he is telling the compiler to do (compared to C). - Hassan Syed
(3) It is a good urban myth - I have heard it on everything from OpenGL to databases = we have to use c because we need performance. - Martin Beckett
(26) @Mathieu a competent programmer can write C++ code faster than the C code. - phaedrus
(102) I politely say: C is faster than C++ - lsalamon
(4) @Isalamon: Reasoning? - GMan
(10) This is stupid. There's no such a thing as fast language. It's the programmer's choice of algorithms that makes or breaks the speed - as well as the optimizations going on in the compiler. "C++ is slower than C" is as true or false as "C is slower than C++". Or Java. Nowadays compilers do so much tricks to your code that there's no way to know what actually is going on, even though some people seem to think so. Even modern processors will alter your instructions. - Joonas Pulakka
(6) @Joonas yep, if I'm dealing with a couple of million data rows that I need to have fast lookups and fast inserts I'll write the RBT implementation in python because it will be just as fast as C++. Why bother with wasting the time and effort in using C++? - Hassan Syed
(65) You're technically correct; C++ can be as fast as C. However, I think that most people aren't interested in what can be done; they are interested in what is done. If you take average-quality equivalent pieces of C and C++ code, the C will be faster. Until someone finds a way to get everyone on a team to write meticulously optimized C++, I'm sticking by my perception a that C is faster. That said, the difference in speed is small compared to the other differences in the languages, so I don't think anyone should ever choose one language over the other based solely on performance. - Imagist
(2) @Hassan: It depends on your algorithms. With million data rows, an O(n2) C++ algorithm is almost certainly slower than O(log n) QBasic algorithm. - Joonas Pulakka
(2) @Joonas: Well if your language have support for Garbage Collector, dynamic length strings, then there are of course more work to be done, if you are not going to do it yourself. And for Java running a VM will take time to translate to native instructions, even if you have JIT. Modern x86 processors are RISC so they will translate to RISC instructions. Which also have its cost, but it is something to sacrifice for if you want backward compatibility and portability. At least you have better languages, to more easily express problems. - emil
(36) Guys, guys! When I asked this question, I had no intent to start a language war! Please don't do so. - community_owned
(2) @Joonas Nobody is saying that algorithms aren't important. But performance is based on a wide variety of factors, and language choice is not a minor factor. - Imagist
(7) @Neil: It's C++. This almost always happens. :) - Greg D
(54) std::string::length is a lot faster than strlen... - FredOverflow
(4) In many cases, the perception that C is faster than C++ boils down to the C compiler in question being more efficient. I do a lot of my development in the embedded world, where C is far more common than C++ for this very reason. The C++ ports of our C code run slower, and we've had several compiler vendors confirm that their C compilers do a much better job of optimizing code. There's nothing preventing a C++ compiler from matching or beating a C compiler, that's just what I've observed from practice. - bta
(5) C++ has some features,most notoriously multiple inheritance, that do make it difficult for the compiler to generate efficient code as compared to C. In these days of Java and Python, though, C's minor efficiency advantages over C++ seem trifling. It used to be worse, with the C++ compilers of the 90's. - Nate C-K
(3) Faster development time or execution time? If the latter, it's not a big issue since by the time your project is done, Moore's Law will guarantee that the finished C++ code will be faster than C would have been at the start. And vice versa. - Duncan
(6) C99 at least is much easier and cleaner than C++, in my opinion. Still, not being able to mess with templates sucks. - Johannes Schaub - litb
@Joonas: Executing the same algorithm with, say Java and C++, do you say you'll get roughly same execution time? If not, wouldn't it talk about the bulkiness of a language? - legends2k
(1) @legends2k: en.wikipedia.org/wiki/Java_performance#Program_speed says "Java's speed might now be comparable with C or C++. In some cases Java is significantly slower, in others, significantly faster." In other words, talking about the bulkiness of a language is simply meaningless and wrong: to talk about it you first have to measure it somehow, and the result varies wildly with what exactly, and how you measure. "Speed of a language" is a gross and misleading simplification. - Joonas Pulakka
(3) And it should be obvious that there are some things different languages do well. If you write code that uses a lot of dynamic polymorphism, then you give the Java version of it a bit of a leg up, because there are some optimisations which JITs do but which C++ compilers can't, based on runtime measurement and prediction of virtual call destinations. It can't be too hard to write a benchmark where that's decisive. If your code has a lot of aliasing, then the C99 version of it might run faster than the C++ version simply because you've correctly used keyword restrict in the C code. And so on. - Steve Jessop
@legends2k, it depends on what. If you just have a simple loop adding numbers, the JIT compiler will probably compile it into almost exactly the same code. Unfortunately (to my knowledge), Java's VM and .NET's VM do not support SIMD extensions, so things like vector math are dog slow. Mono's VM supports this, however, and provides high performance vector primitives. - Matt Olenik
(6) @isalamon: I politely say that C++ may be much faster than what can be written on C. Lookup template metaprogramming. I can multiply matrices NxN (n-parameter) with no counter vars and condition checks. yoo hoo - Pavel Radzivilovsky
@Steve Jessop: Notice that GCC allows restrict as an extension also in C++. Not only on pointers, also on references! - slacker
C is intrinsecally faster than C++.This does not mean you can't write a C++ code that wins against a C code doing the same thing. But if you use some feature C++ provides(e.g. OOP itself...) u add a bit of overhead, you can't do anything about it but stopping using OO stuffs!strlen is slower than string::length since they are different algo (strlen is O(n)); but if you implement a better algo,so that getting the len of the str is O(1),then you have similar algo to C++, and C still can beat C++, since s.length() is a method call which is normally more expensive than a function call. - ShinTakezou
(14) A simple example of where C++ is faster than C is with sorting. std::sort will outperform qsort, almost always. Simply because function pointers cannot be inlined in either C or C++, but std::sort allows you to pass a functor, which can be inlined. A counterpoint to this is that if you pass the same function pointer to both, they'll likely execute in the same time. However, C++ provides a facility that is faster. - Nathan Ernst
@Shin: I wonder why you and others assert some surprising things like that C++ would be intrisically faster than C++ ? C being a subset of C++ (except for some corner cases) the compiler code can be the same. But there is also many optimisations the compiler can perform on C++ code but not on C ocde like inlining references in functions parameter (quite hard with pointers). - kriss
@kriss C faster than C++ I suppose you meant.C is not a subset of C++,rather C++ is a superset of C,but many disagree with this.If you use idiomatically C++(i.e. you use C++'s OO stuffs),then there's a overhead due to how OO things are given to you:there's more code "running" between what you've written in the source and what is actually done.All optimisation possible in C++ are possible in C, of course("map" to the processor);do you think C++ "special things" with "special names" have no pointers under the cover?They have. - ShinTakezou
(2) Most of the slower performance, IMHO, is actual misunderstanding of dangers of deep-copies, passing around objects instead of references or pointers - those copy constructors have work to do, and if you don't do it for the compiler, it'll do it for you. - Chris Kaminski
Knowing HOW to write the code in an optimized fashion, and knowing HOW to take advantage of things like references and pointers can certainly increase code speed. A lot of speed will also come out of how you compile the code, and what tools you compile and link it with. - Alex Hart
Productivity ? Just use python for god sake, and just optimize with C. - gokoon
(1) In response to > "C still can beat C++, since s.length() is a method call which is normally more expensive than a function call", I don't think there is any reason a non virtual method would be slower then a function, is there? - Roman A. Taycher
(1) C++ IS BETTER. END OF DISCUSSION. - muntoo
3
[+142] [2010-02-11 15:14:01] AshleysBrain

The STL is slow is a myth. It is often faster than writing your own containers (except for highly specialist uses like EASTL, but you certainly need an uncommon level of expertise to beat the STL), and modern compilers optimise it quite well. Occasionally you can still find fixed C arrays or containers reinvented "for efficiency," when such code may well be slower (not to mention more error-prone than the STL).


Well, I'd say that myth died somewhere around the big y2k obstacle; at least, I haven't heard it once IRL. - gimpf
(19) I heard this one for a couple years, 2005-2007, before I convinced the person to actually use it. Suddenly the complaints about slow, crummy C++ containers stopped. Sadly, I still can't convince a certain other colleague to stop inventing new string classes. - Greg D
It won't be faster than the equivalent algorithms written using C pre-processor meta-programming. canonware.com/download/rb/tree/tree.h - Hassan Syed
Well, "equivalent" containing the reason for the indifference. - gimpf
(10) It also won't be faster than carefully tuned hand-written assembly, but it doesn't mean it's a good idea or that you should avoid the STL because it's slow. For most cases, it performs very well. - AshleysBrain
(9) Are we talking Iostreams too? - Skurmedel
(4) Good point, you probably COULD make it faster writing your own code to cover just the cases you need. However, you always run the risk of missing something that STL has already discovered in all the years of its existence therefore making your code more likely to have errors and bugs. - Brian T Hannan
I never used STL, mostly because I hand-craft containers to EXACTLY what I need. Also this improves my skill anyway. - speeder
(1) Qt's STL counterparts are far easier to use and read than STL ! - missingfaktor
(1) I'd say they are slow as molasses but it depends what you compare them to. - Charles Eli Cheese
(1) The STL may be slower, but it's also extremely well-tested. Would you prefer an adequately performing program, or a blazing fast one that gives the wrong answers? - Duncan
I have written caches for web systems using map / hashmap and found no problem with performance. Am I wrong... - lsalamon
(9) I think a lot of the perception of "STL is slow" comes from debug builds, where STL use can be slower - but it's a debug build, so it doesn't count (and you're getting the benefit of better checking than using raw pointers and arrays!). - Michael Burr
(1) STL is very fast for what it does. When it's slow is generally when people use it for something it's not intended to do, like compare the creation of an array on the stack to std::vector, a variable-sized heap-based container, and using the default std::allocator. That and, as Michael pointed out, checked STL implementations can be really slow in debug. - stinky472
(1) The STL also does a ton of copying, so if you're not careful you can create a lot of objects without meaning to. I dealt with a design where not passing vectors of objects by const reference led to hundreds of millions of copies. This led to a pretty large slowdown. Changing to const ref made it nearly as fast as raw arrays. - Steve
@Steve - that just sounds like mixing up pass-by-value and pass-by-reference when using a large object. In C++0x, the STL uses move-semantics internally a lot, which can make it a lot more efficient. For example, if a vector of strings reallocates, in C++0x it just moves all the pointers across to the new buffer, instead of doing a tonne of memory allocation, deallocation and copying. - AshleysBrain
@AshleysBrain - I agree with you, but it still doesn't stop people from saying the STL is slow. The thing is that it looks like an array, it behaves like an array, but unike a pointer array its really heavy to move it around unless you use pass by reference. - Steve
4
[+125] [2010-02-11 15:17:22] phaedrus

Old one, but still strong:

You need to learn C first.


How to learn to walk before you run. - lsalamon
(36) you don't need to, but it strongly helps. - Stefano Borini
(35) I completly agree! Having a C background bring tons of bad habits (manual memory mananagement instead of RAII, unsafe types, micro-optimization). As well having a Java background for object oriented programming (over doing tons of classes where templates would have done a much nicer job). - Tristram Gräbener
(14) I always thought that it was, "You should just learn C" :P - Dan Moulding
(12) You don't even need C. When I first learned C++ (before C), I didn't really bring an OO mindset with me. I was essentially writing C, but with cout instead of printf, and some classes instead of structs. - BigBeagle
A long while back, people said you should learn Smalltalk first! - community_owned
(3) @lsalamon, I think that is more a case of: "you have to learn to crawl under barbed wire while people shoot at you - before you can run"! - Martin Beckett
(27) Learning C before learning C++ is like learning to juggle with chainsaws before learning to juggle with tennisballs. Sure, once you've mastered the chainsaws the tennisballs are easy, but it's still not the best learning curve. - MSalters
(1) I learned C++ first and it really made me appreciate the complexities and abstraction of C++. If I had learned C first I probably would have thought that C++ was overly complicated and that I could do it myself rather than letting C++ do the work and me take advantage of that work. - Brian T Hannan
(8) @MSalters, I disagree, C++ is more like juggling little mystery boxes. Sure, they are easier to juggle and catch, but when you do drop one or hit it the wrong way, they end up being dynamite and blowing you up. At least with C, you know what your juggling and know it's dangerous - Earlz
Depends how much you learn. All the techniques you are likely to do away with, or the language itself? Sooner or later, no matter how many class libraries and abstractions you have, you will probably need to write a for loop. - Duncan
(1) @Neil: I get the feeling that, with Objective C, Steve Jobs still wants people to learn Smalltalk first. - Mike DeSimone
(2) If you haven't memorised all those opcodes then I aint interested in you knowing C- it's far too high level. - Martin
I learned C++ before C, and then found C easy afterward (although I find C to be clunky after starting with C++). - Brendan Long
(2) It helps having a deep knowledge of C if you're seeking a deep understanding of C++. It's the way our brain works: from concrete to abstract... exactly like having a good understanding of assembler (any assembler) will help you when trying to really understand C. You don't need C if you only want a superficial understanding of C++; in that case you probably only need a psychotherapist to help you with your suicidal tendencies :-) - 6502
(1) You "need" to learn first C, if you want to learn both. Since going from C to C++ can get some power feelings, while going from C++ to C can result in frustration ( s != "hello" does not work... missing templates; if you need "vectors", "dictionary"... you can't use STL and have to figure out which library is "popular", or "efficient enough", or whatever...) - ShinTakezou
The "C part" of C++ is important to be learned I think. You are saying C like you are talking of everything that is different from C in C++. It's just lame - gokoon
I will never pay attention to a developper who never developped in C before. beware of Java and C# freaks who don't understand the code they are writting. - MiniScalope
@Earlz I prefer the mystery boxes then - 50% chance of getting killed vs 100% in C. - muntoo
5
[+118] [2010-02-11 15:08:55] Tristram Gräbener

You have to manage the memory manually

Ok, it's a bit tricky (and somewhat provocative point of view), but using RAII you can cover almost every situation. For some extreme cases, smart pointers do the work.


(1) +1, good one. Typical example: using a fixed size std::vector<T> instead of new[] and delete[] for a memory buffer. Vector manages the memory for you. Still frequently see the new[] and delete[] versions. - AshleysBrain
(14) But, SOMETHING still has to manage that memory, right? SOMEONE had to write that class so that it could be used without having to worry about the memory management, right? - Jeff Barger
(86) @Jeff Barger: An nobody had to write the GC code in the JVM? - Fred Larson
@Jeff: using RAII your variable is on the heap and memory relasead at the end of the current context (aka next '}'). If you want to keep data on a broader context, use classes, containers (indeed, std::vector DOES manage the memory, but the developer doesn't give a damn shit). Smart pointers are implementations so that you don't have to worry about memory. But with some practice and good code refactoring, you rarely need them. - Tristram Gräbener
(134) The heavens parted above SUN and handed down the garbage collection code, forged not by the hands of man but by a higher power. - BigBeagle
@Tristam: good point about RAII putting it where you really don't need to worry about it. Thanks for the clarification. - Jeff Barger
@BigBeagle: awesome response and great wordage ... some features are so great (for certain things) that it seems that man did not create these things but merely discovered the creation of a higher power. - Brian T Hannan
You can also write compiled C++ with garbage collection... sourceforge.net/projects/bdwgc - Pestilence
(2) @Fred Larson: Correct, somebody had to write the GC code in the JVM; my point is, I don't have to do anything special to take advantage of it - I don't have to write my classes any differently in order to get the benefits. This is not the case in C++ - if I don't use classes that were designed with this in mind, I don't see that benefit. Its more inherent to Java. - Jeff Barger
(27) Most of the bad C++ that I come across is bad largely because of memory leaks everywhere you turn. It makes me cringe when I see people writing that C++ has automatic memory management. It may be automatic if you do everything just right, but it's not automatic in the way that Java or C# take care of most memory management issues for you. My position is that if you don't know how to do proper resource management in C++ (automatic or otherwise), then you're not really a C++ programmer. - Scott Smith
(3) My gripe with Greenspunned GC, aka smart pointers, is that it's slower than "real" GC, even the conservative mark-sweep Boehm GC. - dsimcha
(5) @dsimcha: As indicated in the @phresnel answer, smart pointer vs. GC performance comparisons are generally irrelevant since C++ code calls "new" much less frequently than C# code ("we use the stack"). - nobar
(9) @Jeff Barger: No, you don't have to change your class if you want it through a smart-pointer. How much C++ experience do you have, if any? - phresnel
(4) @Scott: If you don't free all resources (everything from memory to database transactions to GUI elements) correctly, then you're not really a good programmer in any language. - community_owned
(2) Even when using RAII you are still managing memory. You still need to know how it works, you still need to know what you are doing. - Ed S.
(3) Garbage collecting languages are for lazy kids - whatever they do, MOM will clean up the room, hours or days later. - Frunsi
(1) @phresnel: Barger is mostly wrong but there is an exception. At least with boost::shared_ptr, you can't make a shared_ptr to 'this' without the class inheriting from boost::enable_shared_from_this. This should only be a concern in instances where you have control over the class anyway though. - Joseph Garvin
(1) @Ed Swangren: Same with GC and Disposables. - phresnel
@Joseph Garvin: Good point :) - phresnel
@phresnel: Another problem I just remembered is that smart pointers don't work as covariant return types. You /could/ make such a smart pointer if classes automatically contained typedef's to their parent classes (which would be sweet!) but I don't know if anyone else has thought of this so I doubt it's in C++0x ;p - Joseph Garvin
@Joseph Garvin: At least boost's shared_ptr traces the actual type of hierarchies, so you can savely save a "Triangle" in a list of "Shapes", e.g.; I am not sure if it goes so far to also trace completely unrelated types, though. Sidenote: You can use a trick to overload functions on the return type (hint: by introducing a helper class that defines conversion operators) - phresnel
6
[+107] [2010-02-11 17:01:34] Kristopher Johnson

You have to choose a "safe subset" of C++. Don't use exceptions or templates or multiple inheritance or operator overloading or collections or smart pointers or function objects or custom memory allocators, because those features are far too complicated for mere mortals to understand and use correctly.

Truth: The "complicated" parts of C++ are there because they can make programs simpler. Don't prohibit their use because you are not familiar with them or because you've seen them misused.


(24) Well, turns out, templates are too complicated for "mere mortals", let alone "mere mortals" writing any even if really appropriate. - Dmitry
(10) Like any programming language feature, templates can be abused in interesting ways. The same is true of if statements, loops, and recursion. - Joel
(1) I wish I could upvote this one multiple times! - Dan
(1) Yes. C++ can be easy, but also leaves space to be exploited by experts, who can then pack the new nice functionality in a clean interface. About abusal: gitorious.org/metatrace ... I am off - phresnel
(11) The real problem with C++ templates is that they're not powerful enough, not that they're too powerful. They're a Turning tarpit that makes metaprogramming beyond simple generics barely possible but completely unmaintainable. For examples of elegant, readable metaprogramming that can be done with more powerful templates, see std.algorithm and std.range in the D programming language. These were written by none other than Andrei Alexandrescu. - dsimcha
(7) @dsimcha: but unlike D, C++ was never specifically designed to support template metaprogramming so it’s not really surprising that D is better at it than C++. And as a “mere mortal” you do not need to use template metaprogramming (directly). You just use the libraries. - Konrad Rudolph
(5) @Konrad: I agree completely, but my point is that it seems like the consensus among the people who say template metaprogramming should be avoided is that it's "too powerful" or inherently too complicated for mere mortals. My point is that the real problem is simply that it C++ templates weren't designed for metaprogramming, and with properly designed tools mere mortals would be able to use template metaprogramming. - dsimcha
@dsimcha: I would say that templates are absolutely powerful enough, for I have written a C++ compile time whitted style ray tracer (gitorious.org/metatrace , supports arbitrary deep recursion, arbitrary many objects, etc., i.e., the objects and lights are not hardcoded as in the previous two C++ compile time ray tracers), but the syntax is highly inconvenient if you are not absolutely used to it. constexpr's will solve for that to a high degree - phresnel
(2) This one happens with all languages - lost count of how many times people using C# have told me "we aren't allowed to use lambdas". And yet I bet they're allowed to use anon functions in JavaScript (how would they manage without them?!) So as C++0x features become widely available, you can add lambdas to the list of things that your boss finds too confusing and futuristic to sanction. - Daniel Earwicker
(1) This one is true. C++ is full of features you should never use. - Warren P
(1) I'm all about code readability and maintainability, but I hate the often used excuse that accompanies this sort of rule which is that less experienced programmers will not be able to maintain the code. The only thing this accomplishes is to discourage them from improving their skills. - Ferruccio
Concerning exceptions, often they argue against them referring T. Cargill's article (ptgmedia.pearsoncmg.com/images/020163371x/supplements/…) which used a pretty silly chunk of code as an example. - Valentin Heinitz
7
[+83] [2010-02-11 14:50:51] sharptooth

If you use new[], then delete (not delete[]) on the obtained pointer you have a memory leak.

Actually you have undefined behavior. Depending on circumstances either it just plain works or you have a heap corruption, or some other damage much worse than a memory leak, but almost never a memory leak [1].

[1] http://stackoverflow.com/questions/1913343/how-could-pairing-new-with-delete-possibly-lead-to-memory-leak-only

Good call. And I bet it even says explicitly in the standard that the behavior is undefined. But I've never actually read the standard so I don't know. - Brian T Hannan
(1) @Brian: "5.2.3/2: In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression.72) If not, the behavior is undefined. [Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression.]" - GMan
Awesome, thanks! - Brian T Hannan
The selected answer in the question you linked to gives a clear example of how it could cause a memory leak -- basically, any time your array is not POD. Either way, you shouldn't do it. - nobar
@nobar: It will cause a heap corruption and also a memory leak. Having a heap corruption at hand will you care of the memory leak? - sharptooth
(1) Whether or not you care about it doesn't change the fact that it very well can cause a memory leak. But you are right -- it has undefined behavior. It is a bug. You shouldn't do it, for multiple reasons. - nobar
(1) The sad thing is that there's also the myth that delete and delete[] are equivalent... :( - Matteo Italia
Depending on the allocator, it will most likely NOT cause heap corruption but it will not call the destructors of the elements in the array. If the array is composed of concrete classes with destructors, explicit or not, then it can cause a leak. - Andy Dent
(4) @Andy Dent: Most compilers prepend the array with the number of elements, so that new[] returns an address different from the one heap allocation returned. When delete[] is used this is compensated for and deallocation is called for the right (the same) address. When delete is called instead no compensation is done, the address is passed to memory deallocation as is and since it is different from the one returned by the allocation - hence undefined behavior - most likely heap corruption. - sharptooth
(1) Far worse than a memory leak: taossa.com/index.php/2007/01/03/… - Longpoke
8
[+82] [2010-02-11 15:10:21] leppie

If you make a mistake, you blow off your leg.

Most people will die when that happens, and there are far more C++ programmers than can be accounted for taking this into consideration.


(17) Thanks for reminding me of this one. - community_owned
(2) Yes, but what is the average error severity in .NET? Exception, program (maybe) dies. In C++? i bet it's something closer to leaking memory, doing some sort of really bad thing with pointers, or causing one or more programs to explode for no reason. - RCIX
(1) believe me, there are plenty of cases where I see memory leaks in .NET - its almost an anti-pattern to leak objects in .NET event-driver Winforms/WPF coding. - gbjbaanb
Looking at C++ compile errors, I'm still afraid for my leg though... - gokoon
9
[+82] [2010-02-11 15:16:24] phresnel

0) In C++, you must mess around with pointers, that's old and dangerous, use C#

Gee, #include <boost/shared_ptr> or one of the like. Actually, it is often easier to produce mess in your sowonderful C#:

static void Main () {
    foo();
    bar();
}
static void foo () {
    var f = new StreamWriter ("hello.txt");
    f.Write ("hello world");
}
static void bar () {
    var f = new StreamReader ("hello.txt");
    Console.WriteLine (f.ReadToEnd ());
}

"Unhandled IOException: The process cannot access the file 'hello.txt' because it is being used by another process."

Those claims, btw, are often made by those who happen to never have heard of RAII, and about how far you can get without even smart-pointers.

1) #define SAFE_RELEASE(x) ...

without words

2) Heap-Allocation in C++ is sooo slow when compared to .net

Well, uhm, in C++, we use the stack most of the time, thanks.

3) foo=new Foo(); if (foo==NULL) {...}

See 1).

(the following are more compiler related, not sure if they really fit the topic)

Appendix A.0) Porting from MSVC to g++: found g++ bug!!!!

Answer: You must add typename there.


(30) That's not proper usage. You should close the StreamWriter; you did not. Or you should use a 'using' statement. - George Stocker
(54) @George Stocker: That was exactly the point. People often assume that in .net, it is hard to get things wrong. But often, especially when it comes to Disposable objects, the contrary is the case. - phresnel
(7) (hm, can't edit my reply?) I wanted to add, beginners also often assume that the Garbage Collector will solve it all and at the right time, until they stumble over such an exception sooner or later. Unfortunately, in Real Life, many programmers are left alone with their compiler, learning a new language, and employers won't tell them to read a book first. - phresnel
(2) Those will be cleaned up though by the GC assuming they have implemented IDisposable correctly, in C++ depending on the OS you could potentially lock a file for a very long time. Which could happen in C# too if the GC never cleaned up of course, but I think the reality is different. I still think it is much easier to misbehave in C AND C++ than it is in C#. It doesn't mean you can't misbehave in C# or Java though. Preemptive disclaimer: I like C++. - Skurmedel
(4) The "potentially" applies to every programming language. But as long as you stay in the std-c++-lib, and as long as you don't new a stream, RAII comes usually to the rescue. Admittedly, there's a bunch of other pitfalls, but C++ is often frowned more upon than deserved :) - phresnel
(1) Well, looks like I misread your example so I apologize a bit. But what I wanted to say is that it's easier for me to screw up, the frequency with which I do embarrassing screwups in C++ is much higher than in any other language. Overall I agree though, many people have strong opinions about C++ without ever trying it, and obviously people can do robust things in it, otherwise I wouldn't be able to enjoy S.T.A.L.K.E.R later tonight ;) - Skurmedel
(2) So...you're saying that you can't run into problems with filehandles in C++? Don't get me wrong, you're 100% on the money with RAII, but I wouldn't say it's 'easier', when in C++ you have to avoid the same pitfalls and know about shared_ptrs, etc. - Marc Bollinger
(16) I smell a Linux troll lurking here... - erikkallen
(8) @erikkallen: Where? Why? Linux is more about C than C++. And .net is also on Linux, though with another name and not 100% compatible in both directions. - phresnel
(2) @Marc Bollinger: Most of the time you don't have file-handles, just int main(){std::ofstream o("hello.txt"); if(o){o<<"hello";}}. Personally I fail more often in C# than in C++ (e.g. because of missing const correctness or missing builtin copy semantics for clas types), but that surely differs by what one does in that language. Did not want to start a flame here :D - phresnel
(2) +1 just for apppendix part - Naveen
(1) @Skurmedel: You give a pretty good description of C#'s "random destruction" feature: The GC will probably clean things up, you just don't know when. This is why the example program will fail, but only most of the time. - nobar
(2) -1. This is only barely on-topic and seems more concerned with bashing C#. - EMP
(3) @Evgeny: This is what I often hear from ex-C++ now-C# coders. They often give me the impression they moved over to C# for wrong assumptions and/or misunderstandings. - phresnel
Since when is .NET faster at allocating memory than C++? VC++'s new calls malloc and constructs the object, which in turn calls HeapAlloc. GCC's probably does the same, but it might use VirtualAlloc and slice the memory itself (didn't bother to check). .NET has to use Heap/VirtualAlloc, and also construct the object. Where is it faster? - iconiK
@iconiK: The point is that it is irrelevant in most cases whether heap-alloc is faster in .net or not, as stack-alloc seems to be the most common way of allocating things in C++. - phresnel
(3) Garbage collecting languages are for lazy kids - whatever they do, MOM will clean up the room, hours or days later. Until cleanup, the toys are unavailable (lost, hidden, covert, locked ..). RAII would be a solution, but kids don't mind - they can wait (if only they can start playing as fast as possible). - Frunsi
(3) @iconiK: heap allocation in .NET is most of the time nothing more than a pointer increment. The process already has reserve memory allocated from the OS, and the CLR doesn't do free-list lookups and such, as it pretends the heap is unfragmented. blogs.msdn.com/maoni is a good source for how the CLR manages memory. - Joren
Funny trolls here are so funny - abatishchev
10
[+79] [2010-02-11 15:55:08] RED SOFT ADAIR

C++ is less portable than Java.

The opposite is true.


(10) Can you back that up? Any non trivial application is going to need to use code that is going to need platform specific code, e.g. a GUI or maybe something that analyses a file system as two random examples. Just look at the source for ACE or the even in Boost and you will see the lengths that have to be gone to get code that will work under different compiler and platforms. True with a good design you can minimise the platform specific code but you still need it, whether it's your own or a x-platform library that someone has already done the work for you. - vickirk
(10) I have never had to provide platform specific code in java in 10 years of java development. Ok, once or twice I may have had to add a workaround for a bug in a particular platforms JVM. - vickirk
(71) I don't get why it is downvoted. This answer even contains two myths. - Johannes Schaub - litb
(1) Was the op saying that "The opposite is true" is the myth? e.g !(!(cpp_portability < java_portablity)) - vickirk
(3) @vickirk: You're confusing platform-specific interfaces and libraries with the programming language. The language itself may be portable across multiple platforms but the interfaces to the operating system may not be portable. Even portable languages like Python have OS-specific modules, but the language itself remains portable. The same is true for C++. - Void
(3) But think of games, for example. While you COULD build sophisticated games in Java, the lack of JVMs on modern consoles would give you no reason to do so. - Oliver Weiler
(3) Plain C++ is the most portable language. You can compile and run it on each and every machine from Embedded to Supercomputers. - RED SOFT ADAIR
Hey don't get me wrong I like c++ Ok. Sure, anything written in standard c++ using just the standard library will/should compile on any platform assuming the programmer is aware of what is not guaranteed by the standard, e.g. size of primitive types. However my point was that what you can do can only using standard c++ is a whole lot less than what you can with a particular version of the java runtime, so java is more portable. This to me is one of the major reasons c++ last a lot of ground to java, fortunately the next c++ standard will make things a bit better. - vickirk
(5) "Plain C++ is the most portable language" - Surely C is more portable than c++? - vickirk
(19) vickirk: You should try Qt. And then you'll see that even GUI and filesystem stuff can be portable. And with regards to boost: If you use it, your app can easily be portable. But what is under the hood of that library is largely irrelevant, as even Java and every other language in the world is not portable under the hood. - phresnel
(2) You could easily say "Java takes less effort to make it cross platform". C++ can be made so - but it is a LOT of work. - Mordachai
(3) It is still simpler to write cross-platform code in Java... Try to write a portable GUI in C++ for Linux, Winodws and OpenVMS... And do same in Java. - Artyom
(10) Last time I looked (four or five years ago), Sun shipped JDK for three operating systems, and they achieved that level of system-independence (a joke IMO) by using Lowest Common Denominator as the governing principle (that also limited them to those three OSs). The assertion that C++ is more portable than Java definitely was true at that time (Sun required a prohibitively hefty fee to certify JDKs for other operating systems). - just somebody
@vickirk You have never tried to comply with Mac OSX HID guidelines have you? You simple MUST use Mac specific code or you menus will not be proper Mac-style menus. Yes you could pass is arguments to make your JMenu dock to the real menubar, but that has its own issues as a quick google search can tell you. - KitsuneYMG
(1) @kts the property com.apple.macos.useScreenMenuBar solves that unless I've misunderstood your comment, I develop on both mac and linux and never had any problems. Most of the software I use is java based and works as you'd expect on both linux and mac. - vickirk
@vickirk That doesn't solve the problem. In OSX the menu is ALWAYS docked even when no window has focus . That property merely docks the current Window's MenuBar. In the case of JMenuBars it make a value-equivalent MenuBar and docks that. Further changes to the JMenuBar (recent docs, "Windows" menu option) do not effect the application menu bar. Plus there is the whole DISPOSE_ON_CLOSE win/unix behavior vs the HIDE_ON_CLOSE OSX behavior. See: java.sun.com/developer/technicalArticles/JavaLP/JavaToMac for more. - KitsuneYMG
(3) saying java crossplatform is like saying my code is crossplatform because it could run on Windows 95/98/Me/XP/2000/Vista/7 - uray
(2) C++ is as portable as Java. It's the libraries that may not be. - Bruno Brant
@Bruno: At the source level, yes. At the object code level, no; Java has the edge there. (I suppose C++ could be compiled to bytecode that runs on a portable abstract machine, but people don't do that so it's not a realistic scenario; Java object code is more portable in practice. Like you care.) - Donal Fellows
@Donal: I have to agree that, in practice, Java is way more portable. But language-wise, both Java and C++ are portable -- they make almost no assumptions over the environment or platform. The same can't be said of, let's say, COBOL. In COBOL you use the language to specify environmental settings. - Bruno Brant
@Bruno: I think we're in thorough agreement. The only real non-portable part of C++ itself is the fundamental numeric types which are borrowed from C. Java's equivalents happen to be very tightly specified. - Donal Fellows
@phresnel QT has its share of portability issues. Just look at the community forums related to OS X-specific issues as one example. - stinky472
@stinky472: The crux of your post is "OS X-specific". Of course only the lowest common denominator of supported OSes can be the same on every platform. But as soon as you want OS-specific stuff, you have to introduce un-/less portable things, enclosed by #ifdef-scopes or by passing parameters to Qt for which Qt has special behaviour for certain platforms. - In case I misunderstood you, maybe you could post some link? - phresnel
Java being platform agnostic thanks to its virtual machine, I don't get how it couldn't be portable, that's a shame for such a language... I don't think "portable" is the right word for a language such as java... - gokoon
In C or C++ you have portability provided you have a copy of the source which was written for your platform. In Java you can take a library compiled 10 years ago on a 32-bit system and run it on a 64-bit machine without having to recompile it. - Peter Lawrey
11
[+63] [2010-02-11 15:28:47] Johannes Schaub - litb

The Standard allows NULL to be something other than zero, so you should not use 0.

Urban Myth!


I'd say it is only half-myth, in a sense that it's probably much easier to go grep and replace all NULLs with nullptrs when thy finally come to us than it is with 0s. - Dmitry
What is a myth, that NULL is better than 0 or just that null can be something other than zero? - vickirk
(2) Which one is better is an opinion (argumentative and subjective) and is not a myth. - Johannes Schaub - litb
(42) The standard requires NULL to expand to an integer constant equal to zero, but you should still use NULL in preference to a plain 0 when a null pointer constant is desired. Source code should be written (at least) as much for consumption/reading by people as by compilers, and when properly used, carries a connotation of intent that is absent when '0' is used. - Jerry Coffin
(28) @Jerry: Meh. Bjarne says just use 0, and that's what I normally do now too, so it's 2 votes to 1 against you in the C++ community ;-). I don't use 0L when initialising a long, either, or 0.0 when initialising a double, or '\0' for a char. @litb: it's not a myth that you should use NULL, but it is a myth (if it's believed at all) that the reason given is an argument for using NULL. - Steve Jessop
(25) actually there is a serious place where using 0 instead of (void*)0 will break things. It bit me badly. If you pass 0 in varargs function the compiler will push an int. When the called function is expecting a pointer then bad things happen on a platform where sizeod(int) != sizeof(void*). I used to mock people using NULL in c++, not now - pm100
(6) @pm100: Not that using NULL will fix that. NULL is not (void)*0. - GMan
What GMan says. NULL is expressly forbidden by the C++ standard from being an expression of pointer type. Using it to mean a pointer is therefore if anything more mock-worthy, I think it was only kept at all in C++ to help C code compile as C++. In C it might be an integer type or a pointer type, so for portable code you can't use it in varargs there either. - Steve Jessop
(16) This conversation conflates several different issues. A literal 0 in a pointer context will generate a null pointer. In C++, the macro NULL should expand to 0, not ((void*)0) (which was common in some C implementations). The internal representation of a null pointer may be something other than all zero bits. On some exotic platforms, null pointers are some special address other than 0. C++0x is adding they keyword null_ptr because using a literal 0 can be ambiguous in certain contexts (e.g., templates). I assume we'll start defining NULL to be null_ptr then. - Adrian McCarthy
(4) A corollary to this myth is that "NULL is always '0' in C++". NULL can validly be 0L rather than 0, which is fun because I've seen people try to use NULL as a pure-specifier thinking it will always be "0". - Dan Olson
(2) @Adrian, sadly we cannot define NULL to nullptr, because while NULL must be an integer (and so is convertible to int or actually is an int, for instance), nullptr is not convertible to int. In general, i avoid saying "in a pointer context". I just say "will be converted to a null pointer when needed". Because the next question will be, what is a "pointer context"? - Johannes Schaub - litb
@DanOlson, totally agreed :) I had to decide whether to write "zero" or "0", and decided to write "zero" in order to avoid exactly that ambiguity :) - Johannes Schaub - litb
the gcc I used ended up making NULL into nullptr (via a typically baroque set of defines). All I can say is that vararg 0 => crash on 64bit system, varag NULL => !crash. I was surprised that it mattered - pm100
NULL is useful in gcc in that they don't use 0 (as the standard says). It uses __null which is a fancy compiler specific 0 that emits a warning when NULL is use in an integer context instead of a pointer. __null is halfway between 0 and nullptr. - deft_code
@caspin the Standard does not require them to use 0 (that's another myth). Instead, it requires them to use something that evaluates to zero. __null is such an expression that evaluates to zero. - Johannes Schaub - litb
12
[+61] [2010-02-11 14:57:52] mre
  • C++ is inefficient for embedded development

  • C++ is only C with Classes (see STL...)


(4) C++ started out as "C with classes", as that is what they called Stroustrup's first version. It's grown a lot since then. - David Thornley
(15) It's not that C++ is inefficient for embedded development it's just that someone is more likely to utilize a feature of C++ which makes the code no longer real-time enabled. You can create truly real-time C and C++ code, but when you use some features of C++ you may run the risk of making your code no longer real-time friendly. - Brian T Hannan
(2) That article was a nice primer on C++, but was woefully unconvincing, IMHO. The author really glosses over the impact that template usage can have on code size, among other things. The real issue, I think, is that C offers far fewer features that can be easily misused. It's easier to be accidentally inefficient with C++. Inefficiencies in C are almost always far more readily apparent. - Dan Moulding
(3) This myth is, in a sense, self-perpetuating. One big reason embedded developers use C over C++ is because their C compiler typically does a better job at optimizing code than their C++ compiler does. The reason for this is the compiler vendor didn't spend as much time developing the optimization routines in the C++ compiler since C++ isn't designed for embedded use like C is (or so they believe). I have heard this from several different compiler vendors. There's nothing preventing you from embedding C++ if you take your time and do it do it right. - bta
(1) Real-time coding should be an orthogonal concept to C++'s feature set. C++ knows nothing of your threading. THat said, it is very annoying when the std::string class does non-threadsafe things in what looks like threadsafe code. - Mike DeSimone
Properly designed template classes can make your embedded C++ code more reliable. You just have to be willing to write your own templates where needed. I've got templates for object queues, usually used for character buffers but also useful for structures, that are threadsafe because they use atomic state changes (i.e. state changes with a single word write). It's been tested and I don't want to rewrite it for every contained type... hence, template. - Mike DeSimone
@bta: This is why I raise an eyebrow if someone asks me to use a C++ compiler other than gcc. gcc supports so many embedded architectures so well that it takes a lot of convincing. - Mike DeSimone
(5) C++ is -dangerous- for embedded systems. It has many very friendly and helpful constructs at hand's reach but one incautious declaration of a template and your binary grows by a megabyte, one #include and a function call, and you're down by half a megabyte of RAM. On a PC that's nothing. On embedded systems, that makes or breaks the result. - SF.
(1) What a complete load of BS that article is. The argument is basically "C++ is a bit slower, and uses more memory, but you don't have to use those features". Right, so just stick with C. - Justicle
(1) I disagree with Brian. I think for embedded programmer it is very easy to write real time code with C++, and it comes in handy. - Pavel Radzivilovsky
@SF: how is this worse than calling a library function that is unexpectedly fat and thus bloats your binary at link time? - JBRWilkinson
It depends on what you mean by "embedded" - for a modern 32 bit embedded CPU such as ARM or PowerPC with plenty of RAM then C++ is probably fine, but for something low end, like a PIC with 256 bytes of RAM, it's a non-starter. - Paul R
13
[+59] [2010-02-11 15:29:18] Daniel Daranas

C is a subset of C++. Every valid C program is also a valid C++ program.

Truth: C is not a subset of C++. Not every valid C program is also a valid C++ program.


(7) Rather, C++ is a superset of C, but not a strict superset, which is why not every valid C program is valid in C++. - Jasarien
@Jasarien: equally valid: C99 is a superset of C++98, but not a strict superset; so what's your point? - Christoph
@Christoph: just reading at en.wikipedia.org/wiki/C99 I couldn't see any reference to C99 being a superset of C++98 (I've never heard of a C++98 either). I could be wrong though, care to elaborate? - Jasarien
Supersets aside, C and C++ are still different languages and the myth, as I phrased it, is a myth i.e. it is a false assertion which a number of people hold. - Daniel Daranas
(31) @Jasarien: C++ and C have a common subset, but neither is an actual superset of the other; so either both statements are true (with a somewhat dodgy definition of superset) or both are false (if the mathematical definition is used) - Christoph
@Christoph I like this. I'm for the mathematical definition. - Daniel Daranas
I, for one, would like to see this myth become more true, at least. I'd love to use the field-name-keyed struct initialization stuff with structs that do not have methods. Having to leave out so much of C because you want to write a header that works in both languages is a pain. - Mike DeSimone
(13) I was going to say... SOMEONE isn't clear on the definition of "superset" in order for C++ to be a superset, of C, but not a strict superset of C, C++ must be IDENTICAL to C. I think it IS fair to say though that the intersection of C and ~C++ (everything that isnt in C++) is very small. ie, C++ is ALMOST a superset of C. There are a few things that don't work, but it's pretty small... - Brian Postow
I agree with @Brian, it usually doesn't take too much work to get a large C program to compile in C++. Try doing the same with a large C++ program... - BlueRaja - Danny Pflughoeft
(6) With c99 there's quite a bit more that C++ can't do - banister
(1) However, the intersection is very large and encompasses most programs I've written. - Jeremy Salwen
14
[+56] [2010-02-11 15:37:46] Pavel Shved

Calling virtual functions is extremely slow

I've heard it many times, including here, on StackOverflow. Modern virtual tables implementations dispatch virtual function calls quite fast, with small and predicatable overhead, compared to calling usual functions. In the simplest single-inheritance case it requires just an additional access to one memory cell. I started my blog with an "article" about it [1].

[1] http://coldattic.info/shvedsky/pro/blogs/a-foo-walks-into-a-bar/posts/3

(2) But you do need to watch out for multiple inheritance (when in performance critical code with lots of virtual calls). Depending on the compiler you are using, there can be some significant overhead in terms of table size etc. - xan
(17) On modern architecture, this is actually true. Compilers can not, in general, optimize away function calls that are virtual, since they can't be predicted at compile time. The same is true of the branch prediction. A virtual function call is a guaranteed stall, while a straight function call might not be. - Joel
@xan, yes, you need to watch out, measured and checked. Not just ruled out since "they're slow stuff, I know!". @Joel, some of them can be predicted in compile-time. Having studied some of static-analysis, I now suppose that compilers will be much more predictive in nearest years - Pavel Shved
(1) @Joel: most instruction caches have each line provide a pointer to the next line to fetch. Function pointer calls can be dynamically predicted. - Potatoswatter
@Potatoswatter. This is true of normal functions, where the offset is fixed in the opcode, but when you make a virtual call, it means a table lookup first, hitting memory. Note that every alternative to virtual functions will have similar overhead, however. Switch statements are generally compiled similar to virtual calls, while serial if statements are worse because you have to evaluate each if. In general, compilers won't optimize serial ifs into a switch. - Joel
Calling a static function is faster than calling a virtual function, but the runtime decision about which static function to call is slow. - Duncan
(1) @Joel, the processor can very well place the correct next-address value into the cache as part of handling a branch misprediction. This doesn't have to do with static anything. Of course, the dynamic optimization only works as long as you dispatch the same way every time, but it's much better than always missing. The access to vtable is a single cache hit, which is cheap as free—lost in the call frame overhead. - Potatoswatter
(23) I used to wonder if "slow virtual functions" was a myth, so I went and actually ran some timings on the PowerPC we target. I found that a virtual function call had 223% of the overhead of a direct function call -- counting cycles, it was exactly correspondent to a 21-cycle branch mispredict every time. So, Myth Confirmed -- virtual functions really are very slow on some platforms. - Crashworks
(2) @Crashworks, 223% is "3,2 times slower". For the functions with a nearly empty body that is in the bounds of assessments I made. Actually, that may be true and may be not, but it's not always true. The myth is about that "always" stuff. - Pavel Shved
(3) It's not so much the ratio that I worry about as it is the absolute cost - a vcall without a cache miss is 7ns each time on that particular PPC, during which time the pipeline stops dead while the CPU waits for instructions to refill the fetch queue. It's not a big number for everyone, but if you're in a line of work that sweats microseconds, it can add up pretty quickly. - Crashworks
(1) Potatoswatter, et al -- the mispredict problem with virtual function calls is pipeline. The destination of an indirect jump is not known until the address is computed, eg by a load from the vtable. But the instruction fetcher is usually ten or twenty stages ahead of the load unit in the CPU. With a static branch, the fetcher can move ahead to the next instruction by scanning during the decode stage, but with an indirect call, it must wait until after the ALU has produced a number. Some CPUs cache the full address destination of an indirect branch, but many only store a taken/not taken flag. - Crashworks
(4) Saying C is better than C++ because of vtables is B.S. You might want to take a look at your page table faults and context switches which are just as "expensive" and happen no matter what you do... Not to mention the stack smashing protector in your system wasting tons of instructions to try and fix your bound violation errors that are only existent from using C/C++ in the first place. - Longpoke
(2) You make the (wrong, just to be clear) assumption, Longpoke, that all programming is done in an environment with page tables, context switches, etc. Shocking fact for you: the overwhelming number of processors in use on the planet are in restricted, embedded environments. - JUST MY correct OPINION
(22) Virtual calls are more expensive - and in most cases it doesn't matter because they are not in the hotpath. As for the ones that are in the hotpath, how would you have written it in C? You either are re-inventing virtual calls in C, or you are avoiding them, usually at a loss of code clarity. Either option is still open to you in C++. - Eloff
(1) If it is really in the hotpath, the vtable will be in the L1 cache and you'll be OK. Truly, don't worry about doing virtual inheritance. (Avoid multiple inheritance if you can though, but that's because it is horribly unclear and not because it is slow.) - Donal Fellows
(3) Worrying about the overhead of an indirect virtual function call in contrast to a function pointer call is like worrying that the things you are keeping in the glove compartment of your car is making it less fuel efficient. - stinky472
I have seen end to end solutions with and without virtual functions. The speed difference can be huge. There are libraries (written by very competent folks) which avoid dynamic polymorphism for performance reasons. Virtual functions can cause significant loss of performance if a small virtual function called frequently and does most of the work. Heavyweight virtual functions are no problem. - user401947
(2) Compared to a normal call, virtual calls inhibit the inlining pass. That means that normal calls will sometimes be a lot of faster when they are inlined. - Johannes Schaub - litb
@CrashWorks, it is not valid to compare calling a virtual method versus making a simple function call. These two things do NOT do the same thing. If you want to make the comparison valid, change the "C" code to invoke a function pointer stored in a structure. This is exactly the redirection that virtual methods give and is also used in much "C" code such as interrupt tables and openssl. You really need to compare apples and apples. - Jon Trauntvein
15
[+55] [2010-02-11 18:20:33] paercebal

C++ FQA Lite [1] is a C++ reference

FQA Lite is an aggregation of bad-faith-formulated self-contradicting criticism of C++ written by someone with too much time on his/her hands using it to practice biased argumentations and written diarrhea.

My prefered quote: http://yosefk.com/c++fqa/exceptions.html#fqa-17.4

WARNING - cyclic dependency between C++ features detected! You see, exceptions are a must in this language so that you can handle errors in all the functions which fail to look like functions, such as constructors & operators. Then it turns out that you need constructors to work with exceptions - unless each and every piece of memory you acquire is not immediately assigned to some smart pointer, your code is not exception safe. This is known as "Resource Allocation Is Initialization" (RAII) in the C++ community; it's supposed to be a good thing.

Disclaimer: Note that FQA Lite can still be useful when one needs to know the little known corners of C++... Just ignore the gratuitous bashing

[1] http://yosefk.com/c++fqa/

(23) I hate the FQA with a passion. - GMan
(1) FQA lite is a great place to pull 'urban myths' and anti-C++ thoughts. - Paul Nathan
(22) @GMan : I'm feeling more something like pity... There is a lot of passion in FQA Lite, and I sometimes wonder about the depth of the pain suffered by the author to have him rant with so much detail... - paercebal
(21) ... too much time to write a rant, not enough to learn the language. - David Rodríguez - dribeas
(9) I liked this one: How are you going to figure out whether your program manages resources correctly or not when it's littered with smart pointers of different kinds, especially in case there's any non-trivial scenario there, like the cases when "ownership" (the right & duty to dispose a resource) is passed from object to object... by umm, thinking? - Skurmedel
@Skurmedel: Lol about the thinking :D - phresnel
(34) I actually found the C++ FQA interesting (though it's been a while since I've read it - hopefully it hasn't gotten worse since then). While there's a lot of over-the-board hype, it does point out areas of C++ that are problematic. Anything as complex as C++ is going to have a lot of problem areas, and C++ might be a more problematic situation than most complex systems because it was hampered by the requirement that it be backwards compatible with C (which is also one of the main reasons for its success). But, pointing out and learning about those problem areas is useful. - Michael Burr
(1) @Michael Burr: I agree, somewhat: This is why I added the "disclaimer". FQA does indeed a good job of pointing dark corners, but the analysis of the problems, and the solution (use C instead, or C#, or whatever, but NEVER C++) are both too much biased and wrong to consider FQA anything else than a real-life thesis on pain and hatred. - paercebal
(6) I do like this quote: If your application is not CPU bound, you aren't getting any benefits from using an unsafe language like C++ except for extra quality time with the debugger - BlueRaja - Danny Pflughoeft
(3) Ooohhh, thanks for the reading, really made my day! And very true, as was pointed out by others in these comments. And for the hype? Well, in my opinion, it is a perfect counter for that "the real hardcore programmer, not some script-kiddie" attitude that you guys (C++ fans) demonstrate a lot. :-)) - Fyodor Soikin
(1) I started using C++ very early on in the language, and I suspect the author of the FQA also did. I think someone who had been given good books like the high-quality C++ books of today, would have been able to use C++ to much better effect, and would not have come to hate C++ as the FQA author (and I) generally do. I admit my bias is mostly an accident of history; I used some of the worst C++ compilers ever made, and some of the worst class libraries and frameworks ever made. MFC anyone? - Warren P
@Warren P: I understand somewhat. I'm working with cross-platform code that MUST support Solaris native compiler, and there's no shortage of failures this crappy excuse for a C++ compiler brought on my head (mostly runtime linkage failure because it doesn't understand "const" correctly inside signatures)... Still, FQA is something like a full-time hobby, which means a lot of hate, which leads to suffering, which leads to the Dark Side... But I disgress... ^_^ ... - paercebal
(5) Yossi Kreinin is biased i(t may have something to do with his area - image processing on some specialized hardware), but he has a point. FQA is a great read. The hatred is against the language too, no doubt, but also against those hypocritical C++ fanboys advertising the language as something, it is not. And against creators, who claim to be practical, while trying to invent some ideal language, in which library writers have the powers of compiler developers. - Maciej Hehl
(2) @Maciej Hehl: When I read "WARNING - cyclic dependency between C++ features detected!", then I know the author's advice is biased and fallacious. When I read the contempt and bad-faith in his comments, I feel insulted. While I'm not a fanboy, when some funny guy declares "RAII is useless", sorry, this guy's advice is of NO VALUE. I don't care about where he works. FQA is NOT a great read. It is painful and insulting and immature. FQA is the "tabloid for programmer languages". Perhaps you'll find some truth inside, but it is time-consuming to separate it from the bullsh*t. - paercebal
Don't mix it with C++ FAQ (not FQA!) Lite: parashift.com/c++-faq-lite - rursw1
I also like a lot more of parashift faq. - Coyote21
16
[+48] [2010-02-11 22:10:18] Andomar

There are developers who understand C++


(3) Not such a bad answer, there are an awful lot of developers out there with a poor understanding of the language. I'd also say that only 5% (based on gut estimate rather than evidence) of all c++ users completely understand the language, it has a lot of dusty corners. - vickirk
(8) This can be said of any language, anywhere, anytime. "There are mathematicians who understand mathematics" - choose whatever discipline. If its non-trivial, then the idea that anyone knows all there is to know about it is goofy. - Mordachai
(9) No way is it 5%. Perhaps 5% of C coders understand C, ie. know all the flags to printf and the odd corners of string.h funcs. Nobody understands all of C++ and the STL and Boost - Martin Beckett
(10) A friend of mine gave an "Advanced C++ Programming" talk once and started by asking the audience to evaluate their c++ skills on a scale of 1 to 10.After most of them said "5", he told them how it works: 10 - Nobody, 9 - Jesus, 8 - Bjarne Stroustrup, 7 - The best C++ hackers.Then he told them that he'd rate himself around 4 and continued with his lecture .. - Emil D
(2) I'm happy when 5% of my fellow C++ developers understand how to write correct code that doesn't leak memory like a sieve. - Scott Smith
(6) If even Stroustrup understood C++ we would not have had export, exception specifications,nor would have template metaprogramming taken everyone by surprise when Unruh first demonstrated and Veldhuizen built the first TMP library. The great thing about C++ is that is is not the corporate market tool of MS or Oracl with a guru appointed to invent the next revolution - Lance Diduck
(1) Jim Coplien: "There're 15 people in the world who understand object oriented programming, and I am one of them" - Pavel Radzivilovsky
@Pavel: and even Coplien didn't claimed to understand C++, just OOP. - kriss
17
[+47] [2010-02-11 15:19:24] philsquared

Modern C++ style is MFC style

Macros are easier to use than templates


(2) +1 for the macros - kikito
(12) I haven't seen "modern" and "MFC" in the same sentence in a long time. Qt, maybe. - Rob H
I worked on a project just last year where all their existing C++ (written within the last year or so) was MFC style. - philsquared
(6) How is Qt modern C++? It is not even exception safe yet. - Nemanja Trifunovic
(8) I'm only just starting to get my full eyesight back after looking at my first MFC source code a while ago. - dreamlax
(1) @Nemanja, 4.6 IS exception safe - in the sense it will eat all exceptions getting to an event loop. Qt does not, and CAN NOT use exceptions; how do you throw an exception in the slot and be sure someone can handle it? Most of the time the slot is not even called by your code. - iconiK
@iconK: doc.trolltech.com/4.6-snapshot/exceptionsafety.html " Exception safety is not feature complete! Common cases should work, but classes might still leak or even crash." - Nemanja Trifunovic
(2) @Rob: The Qt moc is a nice language, but it's little bit outside what we can really call C++. - Ken Bloom
I have written Windows GUIs using the Win32 API, OWL, MFC, WTL, Qt and WPF. If I needed to build a GUI today, MFC would be my last choice. - Ferruccio
18
[+45] [2010-02-11 17:37:13] pm100

Exceptions are a really bad idea, slow and complicated to understand and maintain

Exceptions are a really good idea, clean and elegant an make code easier to read

EDIT: I have heard both passionately expressed. Since both cannot be true and each camp is full of smart people who care then they both must be myths

For the record I fall into the pro-exception camp.


(3) Are both of these myths? - Johannes Schaub - litb
goto is IMHO better than an exception directly to an enclosing scope. Exceptions have a time and a place, but pretty they are not. - Potatoswatter
(2) @Johannes no, only the second. The first is true :) - Daniel Daranas
(2) I like to litter my code with result code checks every couple of lines w/ gratuitous use of conditional clean-up blocks. - Pestilence
(7) Checked exceptions are a bad idea, as is replacing error handling with exceptions. If you know how to recover, you should. E.g. don't throw if your network connection failed, as that's an expected result. Back off and retry a few times. Throwing an exception for every situation that goes even slightly wrong is expensive. - Duncan
(5) Exceptions should be reserved for the really crazy and catastrophic stuff, like out of memory or divide by zero. Python uses an exception for StopIteration, but it's not recommended in C++. - Mike DeSimone
(37) Can't remember which author I was reading, but the point I liked (and agreed with) about exceptions vs. result codes was this: Result codes are an opt-in mechanism, exceptions are opt-out. Programmers can ignore return codes, but they can't ignore exceptions. - Scott Smith
(4) @Scott: I see you've never met a programmer that writes try { /* code goes here */ } catch(...) {}. It's opt-out, to be sure, but it's also pretty ignorant. - Mike DeSimone
@Mike If I understand correctly, Python's somewhat unique use of exceptions is due to the fact that the underlying implementation of exceptions is pretty fast compared to the rest of the language. - Imagist
(2) @Mike: Yes, I've seen this too many times. But when you see it, it's obvious. Ignoring a return code is much harder to spot. - Scott Smith
Exceptions are very helpful, but when misused, turn the programmer's life a pain! Well, like everything else. After saying that, I still have to controversial state that I actually don't like to use exceptions. Yes, exception denial, but not an extremist one. I use them when I find it's strictly necessary and/or unavoidable. Also, I'd like to point to a great discussion on this subject (C++ exceptions): bit.ly/cpp-exceptions - jweyrich
@Scott: Too much boolean logic here: that is not because something is true that exactly the opposite isn't... both using exception or other programming styles can be great or horrible. OK, ignoring a return code is not easy to spot (but compilers do it quite well), but using exception can lead to very hard to spot memory leaks (RAII is mostly about avoiding that kind of memory leaks). - kriss
Duncan, my gameserver code retries when the connection fails, but before that, the network lib I use throws an exception to notify my gameserver code that the connection did in fact fail. It's about levels of abstraction and separating responsibilities. - Stefan Monov
19
[+43] [2010-02-11 16:21:31] Daniel Daranas

C++/CLI is C++.

Truth: C++/CLI and C++ are different languages.


(5) oh yes! It's not at all C++ runing on a virtual machine. It's a complete new language. (Or maybe where you talking about Command Line Interface? :p) - Tristram Gräbener
@Tristram: No, I was talking about the C++/CLI programming language :) - Daniel Daranas
Daniel don't got it. - speeder
@speeder Excuse me, what do you mean? - Daniel Daranas
(3) @speeder: CLI is "Common Language Infrastructure", the .net runtime. C++/CLI is a C++ dialect (some might call it a bastard) being compiled to IL (.net's assembly language). - David Schmitt
@Daniel, @David: Tristram was being more or less ironic. I know what C++/CLI is (and I find the concept awfull btw...) - speeder
@speeder Ah no, I was totally sure that Tristram was joking in mentioning the Command Line Interface. - Daniel Daranas
(8) Sorry for the misunderstanding. I was joking. C++/Cli (from .net) is indeed a really awfull language. - Tristram Gräbener
(10) I am a fan of c++/cli. - Andy Dent
20
[+35] [2010-02-11 15:07:56] John Dibling

C++ is a horrible language. [1]

It's not the language that's horrible, its the programmers who use it in a naive way. And just as there are bad C++ programmers, you can hardly swing a dead cat without hitting bad programmers in [insert favorite language here].

C++ is an Object-Oriented language.

C++ is a multi-paradigm language. It's not object-oriented in the sense that "everything is an object" the way it is in Ruby or .NET languages. C++ supports object-oriented programming, but it also supports generic programming, functional programming, and just about any other programming paradigm you can imagine.

The STL is Object-Oriented.

According to A. Stepanov [2], no, it's not.

[1] http://article.gmane.org/gmane.comp.version-control.git/57918
[2] http://www.antiquark.com/escape/public_html/stepanovusa.html

(28) Yeah, given the languages that have come into existence over the last 20 years, I think C++ is a pretty horrible language. Of course, this is an entirely subjective call, so I'm not really sure that it qualifies for "urban myth" status. - Greg D
(2) Allthough this is true, it adds no value. - Hassan Syed
C++ is not horrible, it's just plain butt ugly! I wish I knew it though :) - leppie
(10) There are plenty of horrible aspects to C++. Whether the language as a whole is "horrible" is very subjective, and not really an urban myth. Just opinion. - jalf
(1) No matter how ugly the language seems at the surface, the things you can do in C++ -- while generating code without any inherant statistical run time implications -- is mind-boggling. - Hassan Syed
Parts of C++ may be nasty, but other parts are excellent. The SC++L/STL are pretty unique, based on a generic rather than OOP implementation. - AshleysBrain
You all should love hating on my edits! - John Dibling
@John: Nah, your edits are fine. I'd vote 'em up if they were separate answers. :) The STL is definitely not OO, and C++ definitely is multi-paradigm, especially with the new stuff in 0x. - Greg D
Well, it is not "pretty" either. I would not say it is "horrible"... but, at least on its current implementation, it is a bit ... unorganized? cluttered? I can't pick the word. - kikito
(1) @egarcia: I'd use the word "organic." :) - Greg D
(1) Why the downvote? If people claim that C++ is a terrible language, why doesn't that count as an urban myth? - David Thornley
(4) @David: Urban myth's are: Things commonly considered true that aren't. Whether something is ugly or not isn't objective; it can't possibly be false. - GMan
And it can't be true either ;) Not in a factual sense. - Skurmedel
Whether C++ is pretty or ugly is orthogonal to my post. I said the myth was that C++ is a bad (eg horrible) language. - John Dibling
(1) Stroustrup quote = "there are two types of language; those people complain about and those nobody uses" - Martin Beckett
(3) @John: Bad is still subjective. - GMan
@Martin I have nothing but respect for Stroustrup. However, that quote isn't true. Python is widely used and with the exception of whitespace complaints, I hear very little negative about it. - Imagist
@Imagist: Which is exactly why I don't like Python, ..., d'oh - phresnel
@phresnel You don't like Python because I hear very little negative about it? - Imagist
@Imagist: Heh, no, because of the whitespace thing. But I also know it is an otherwise excellent scripting language ;) - phresnel
@Imagist and the GIL, and the use of 'self' and a bunch of points around deployment and JIT. There are enough complaints about Python to show that it is a very healthy language ;-) - Martin Beckett
@John: actually, I've much more troubles with code written by "good" C programmers. With enough abstraction obfuscation is not needed any more ;-) - kriss
-1 a language can absolutely be horrible - BlueRaja - Danny Pflughoeft
+1 but I think it is worth noting that C++ is such a powerful and flexible, multi-paradigm language that when bad coders get their hands on it, the results can be a lot more disastrous than if they were using, say, Python. - stinky472
"The STL is Object-Oriented". Many people think that just because STL has classes it should be OOP. I guess those people have no idea what is real OOP. - user401947
21
[+30] [2010-02-11 22:45:23] Tom Smith

"It's more straightforward to use char* than std::string."


Wow, this is such a "well-known" myth. Char* can really eat your time. - phaedrus
Nah, it depends, in many situations a const char* does its job well. Any time you need a const string (and don't start with "i18n" arguments..) - Frunsi
char* is also necessary for inter-operation with C libraries, or pre-STL C++ code. - dan04
@dan04: with pre-Standard C++ code. The STL has nothing to do with std::string. - James Curran
@dan04: You still can use the c_str method on a std::string; - Atmocreations
22
[+29] [2010-02-11 16:48:47] Martin Beckett

Arrays and pointers are the same thing (ok really more a C myth)


Only intermediate programmers :) - BlueRaja - Danny Pflughoeft
(3) They aren't? When did this happen? - Lajla
(3) @Lajla: When the first C compiler was written. - Billy ONeal
(1) sizeof(int[10]) != sizeof(int *), but that is only difference I can think of. - ralu
23
[+29] [2010-02-11 18:45:13] Artyom

There is such language Unmanaged C++.

This drives me crazy! There is no such thing unmanaged-C++. There is C++ and some other languages called C++/CLI. C++ is not managed.


(21) It's a microsoft-ism. That explains it all :) - Jay
(1) Not managed yet. en.wikipedia.org/wiki/… - KitsuneYMG
(3) Since it's not entirely out of left field to – in a Visual Studio context – refer to C++/CLI as simply C++, it makes sense to sometimes disambiguate by referring to standard C++ as unmanaged C++. In fact 'unmanaged' serves the same purpose as 'standard' does in my previous sentence. It's just an adjective, not part of the language name. - Joren
«C++ is not managed.» Why people emphasize the wrong word(s) in negative sentences in English? (Honest question, I've seen it too often) I was tempted to read that as «C++ is managed»... - marcus
24
[+26] [2010-07-27 00:33:25] user401947

C++ is not a modern language. It is superseded by Java and C#. This one is totally wrong and makes me laugh every time I hear it. Many of my IT friends believe it. Actually, C++ provides more abstraction mechanisms than Java or C#. There is a spin off to this myth.

Newer versions of Visual Studio don't support C++. I heard it from IT folks as well. Some of them believe that Microsoft stopped upgrading its C++ compiler sometime after the introduction of C#.

It is very hard to write exception safe code in C++ compared to Java because of memory leaks. Wrong again. Memory leaks are only a small part of exception safety. There is more to exception safety than memory leaks. Garbage collection helps with memory leaks only.

It is hard to write multithreaded code in C++ compared to Java and C# Wrong. Multithreading is hard in Java and C# as well. Multithreading is a complex and completely different programming paradigm. Once you mastered the art of parallelization, you can use C++, Java or C# to do multithreading.

Java isn't slower than C++ This isn't true. Face it, C++ allows to do more low optimizations, because it is a native language. Competent hackers can cook up highly optimized C++ code which can't be matched in Java no matter how hard you try. But it is true, that incompetent C++ programmers can screw things up easily.


"Newer versions of Visual Studio don't support C++" this made me laugh. :) - Matteo Italia
(2) It is actually impossible to write correct multithreaded code with standard C++ and without some implementation specific support. Correct multithreaded code requires compiler support. C++ standard (current) doesn't give that. - Maciej Hehl
If you think VS does support C++ try compiling this: int main(){return 0 or 0;} - Gabriel Schreiber
(3) @Maciej Hehl - of course you need implementation support: some (old) CPUs do not even have the hardware to support context switching. IMHO a thread is not really a proper thing for a language to concern itself with, a thread is a hardware artifact. Langs that make threads first class data types are either abstracting hardware (thread aware C variants) or are exposing part of their VM runtime (say, Java). - Eric M
(1) Visual Studio never supported C++. Newer or not. It only supports a subset significantly different from the whole thing. - Gabriel Schreiber
however easily bad programmers write slow code in C++, it's infinitely easier to write slow code in Java, and many do a very good job of that. It's far easier to write much faster code in C++ without trying. You really have to think to do it in Java. - Dov
25
[+23] [2010-02-11 17:21:09] Adrian McCarthy

Myth: It is possible to use the STL correctly while in exception denial.

A few STL methods throw exceptions (e.g., std::vector::at). More importantly, the container classes expect the allocator to throw std::bad_alloc when an allocation cannot be satisfied.

If your local coding standard enforces exception denial and thus you disable exceptions in the compiler, these errors crash or corrupt data in STL calls, beyond the ability of the calling code to anticipate or handle the problem. You cannot even rely on RAII to clean up on the way out.

If you permit the compiler to generate exceptions, but disallow code from outside the STL from using try and catch, then you still cannot rely on stack-unwinding and RAII to clean up when an error is thrown from within STL. The unwinding only happens up to the highest point the exception is caught.

And, lastly, the STL containers expect the contained objects to be copyable. If you live in exception denial, what do you do if you can't guarantee success from a copy constructor? You can't throw an exception, and there's no way to signal a failure.

The design of the STL assumes the caller isn't in exception denial.


The STL mostly doesn't generate exceptions, it passes them through from underlying mechanisms. How the situation different whether you use the STL reimplement its functionality? - Potatoswatter
@Potatoswatter: I've edited the entry to address you question. - Adrian McCarthy
Okay, but note that the allocator doesn't generate exceptions; new does, and it's not really part of the STL. And you can get that cleanup if you change to int main( int, char** ) try { /*code*/ } catch( ... ) { throw; }, otherwise being in denial. (Repeat for other threads.) - Potatoswatter
(1) Whether the exception is thrown by new or a custom allocator, the containers still expect an allocation failure the throw rather than return a magic value (like a null pointer). In some implementations. the STL containers catch and rethrow the bad_alloc in order to do some necessary bookkeeping. - Adrian McCarthy
+1 for exception denial. I had to work in a system with such standards for a long time until people started to catch on to what I was saying about this. - stinky472
26
[+22] [2010-02-11 18:47:17] Thomas Matthews

C++ Exception Handling Uses more Time & Space than C

This is one misconception that prevents C++ from being used on Embedded Systems. The fact is that the equivalent exception handling in C amounts to the same time and space (perhaps a little more). The issue is that people don't write the equivalent exception handling in C; exception handling is generally ignored by C programmers.

C++ Virtual Tables occupy more time & space than C

Again, most people haven't implemented polymorphism in C. Also, programs can be written in C++ that don't use virtual functions or polymorphism.

C++, in general, uses more space and time than C.

An equivalent program written in C would use the same space or more. It may use more because some of the issues already in the C++ language would have to be added to the C language program.

C++ is not the Best Language for XXXXX project.

This comes down to price, duration, and skill sets (at least). A language that is best suited for a project (due to language features) may not be the best fit for the shop, especially when few people have experience in that language. A small team of experts in FORTRAN can develop more correct and robust software than a large team of newbies using a popular language. C++ was designed to be a generic language: it covers a wide base of requirements for many projects.

The Size of a Structure (class, etc.) is the sum of the size of the members.

People forget that compilers can add padding between members.

Class Names must begin with 'C'.

Another thing started by the MFC...

Functional Code Must Be In A Class.

C++ still supports free standing functions. Often, free standing functions are a better solution than members in classes.

The inline keyword forces the compiler to inline code.

The register keyword forces the compiler to use a register for variable.

These are only suggestions to the compiler. The compiler can ignore your suggestions.


(4) You may think that exception handling takes no extra time as long as the error doesn't occur, but unfortunately this is not true. The program has to do a lot of bookkeeping in order to know how to recover in the rare event of an exception. agner.org/optimize/optimizing_cpp.pdf 6.27 - Arthur Kalliokoski
(3) Too many myths in one answer... - Macke
(2) The bookkeeping for Dwarf2 exception handling does not affect runtime performance in any measurable way. It does make binaries slightly bigger, causing a load time increase, but even that hardly makes any difference even on embedded systems. Throwing an exception, on the other hand, is much slower than returning error codes (1 µs for throw and catch, 1 ns for returning NULL pointer and testing the return value, benchmarked with GCC). Because of this exceptions should only be used for exceptional situations. - Tronic
(4) exceptions should only be used for exceptional situations. - exceptions should only be used for exceptional situations. - exceptions should only be used for exceptional situations. - BlueRaja - Danny Pflughoeft
@Arthur: Zero-cost try code does exist. I imagine that it costs more to throw in such a scenario, but you can on some compilers/platforms get try for free. - DeadMG
+1 for "The compiler can ignore your suggestions." - Lazlo Bonin
27
[+17] [2010-09-26 02:05:07] Bartłomiej Siwek

iostream is a lot slower than stdio.h

Reason why iostream performs poorly compared to stdio is because it synchronizes its buffers with stdio ones (in order to ensure that output to the screen from both libraries follows the order of calls in the code). A simple call solves the problem by disabling synchronization:

ios_base::sync_with_stdio(false)

(1) As all the C-backwards-compatibility hacks, this is the stuff the makes C++ a worse language. - Matteo Italia
28
[+14] [2010-02-11 15:18:05] Macke

That it's just "C-with-classes" or "Complicated-Java-without-garbage-collection".


29
[+13] [2010-05-13 13:40:52] Johnsyweb

Perhaps more of a DailyWTF than a myth, but here goes...

The lecturer at my alma mater who taught me C++ taught our class that in this example:

for (int loop = 0; loop < 10; loop++)  {
    // Do something with loop
}

... loop would be incremented at the end of the block and in this one:

for (int loop = 0; loop < 10; ++loop)  {
    // Do something with loop
}

... loop would be incremented at the beginning.

Of course, as soon as we started using for-loops in the labs, most of us learned that this was nonsense.

However, five years after my graduation a young guy joined my team and during a code-review he explained that he was pre-incrementing his loop variable so that it was incremented at the beginning of the block. When I asked him if he was taught by [name withheld] it transpired that he was. I dread to think how many graduates left the same university with this misconception.


(1) If the loop variable is a vector<int>::iterator gcc generates different code. If you switch the optimizer on the difference is gone. - Eddy Pronk
(3) @Eddy: but the increment is still done at the end of the loop, regardless of whether it's pre- or post-increment, and as long as there are no side effects, the result will be the same. - Matt Curtis
(2) You know... I also "learned" that somehow. Although I found myself that it doesn't work in that way, a bell of suspiciousness was still ringing in my head. Your post was like a psychoanalysis, it got mind-purifying properties. Thank you! - doc
(1) I dread to think how many graduates left the same university with this misconception - if this was the worst misconception... no harm done (it will manifest at the first test run). Now, other myths ("Problem X is NP-hard", or "use rand()%10 to get a uniform distribution of integers [0,10)"... these are the things that cause real damage.) - sehe
@sehe: At least one guy made it past the lab sessions and through graduation without realising the error, which is a concern. But yes... there are worse misconceptions in the field. - Johnsyweb
Basically, learn facts and learning (how to approach problems/knowlegde) in university, learn the skills yourself and stay awake. (PS. would the case of the strange-loopy lab coworker not really come down to: he never learned to test his <strike>code</strike> assumptions? The working of ++ is immaterial there) - sehe
30
[+12] [2010-11-02 17:08:48] Martin Beckett

Early C++ programs flushed down the toilet grew into alligators in the sewers

(or am I getting urban myths confused?)


31
[+11] [2010-02-11 15:50:12] Jerry Coffin

Your comment about TR1 shows something of a misunderstanding. TR1 was never intended to be a change to the base standard. TR stands for Technical Report, which means it's a separate document about whatever is specified in the associated standard -- in this case, C++.

It's not a proposed change to the base document that failed. Rather, it's (essentially) a whole new standard associated with the original one. Although it's only really intended to be useful in conjunction with the C++ standard, otherwise it has essentially the same status as the C++ standard itself -- i.e. anybody who wishes to do so can provide a conforming implementation of it.

It's also worth pointing out that nearly all of TR1 has been accepted into the draft standard for C++ 0x. The only part that's been changed to any significant degree at all is the random number generators. As such, although TR1 itself isn't (and never will be) part of the C++ standard proper, essentially the same things under slightly different names (I.e., in namespace std:: instead of std::tr1) will be part of of standard C++ relatively soon.

From a practical viewpoint, I'm hard put to figure out why anybody would care either way though. For most people, the standard is important primarily to the degree that it allows portability. From that viewpoint, TR1 is much more "standard" than support for export, for one obvious point.

Edit: As to whether TR1 and its contents will go away anytime soon, I consider it quite unlikely. The situation has been discussed [1] before. I'd give considerable weight to Peter Becker's answer -- as current C++ 0x editor, he's probably more aware of this issue than anybody else.

[1] http://groups.google.com/group/comp.std.c++/browse_frm/thread/ff5dacf64e5fc9c8/7cebb6c85031ab70

(1) The performance TR on embedded systems was not accepted into C++03 at all. And both were in fact formally accepted, as neither proposed to change the standard. That's why they're both reports - essentially ISO blessed essays. - MSalters
An excellent comment, except your last point "who cares". I care and don't use the tr1 in production code because I'm leery it might someday be removed - Steve
(1) @MSalters:When you get down to it, what is the standard except an ISO blessed essay? - Jerry Coffin
32
[+8] [2010-02-11 15:48:36] Earlz

Myth:

Everything is an object.

(I really wish it was sometimes)


(2) Hey.. That's true in Ruby! (I'll be quiet now.) - Trevoke
(1) I know, that's why I use Ruby and C in all my hobby projects, I'd rather everything be an object or nothing! - Earlz
(34) Who holds such a ridiculous belief about C++?? - Mordachai
Generally I find more people who don't realize that something is an object when it actually is (ex: const int x), than people who think that something is an object when it's actually not (ex: functions). - stinky472
(1) @user374980: Huh? The primitive data types of C++ (rule of thumb: those that are also in C) don't give you objects. - phresnel
33
[+8] [2010-08-16 19:53:08] David Cary

Myth: C++ should be the first programming language a student learns.


(4) Agree. First programming language must be assembly. - Pavel Radzivilovsky
(3) No, actually you should start with a magnetic needle and steady hand... <_< - Matteo Italia
I object it should be on world's first computer en.wikipedia.org/wiki/Antikythera_computer - Xinus
I object, we should really have started with butterflies - Joe D
34
[+8] [2010-05-19 16:47:34] Clifford
This also hold for people who think that embedded system is likely not something that can run Linux. - ralu
35
[+7] [2010-07-05 06:16:10] dan04

Myth: C++ is high-level and lets you avoid C features.

The inclusion of most of the STL in the C++ standard library did add some much needed high-level data types. But they aren't integrated into the language itself: The core C++ language is still very C-like.

"abc" is a const char[], not a std::string. You can write int x[] = {1, 2, 3}; but not vector<int> x = {1, 2, 3}; (until C++0x becomes popular). this and argv are pointers.

The C++ standard library isn't consistent about using the modern style. fstream takes a const char* for the filename, not a std::string.

Thus, you can't understand C++ without understanding C-style arrays and pointers.


Yes but you can avoid having to do low level stuff all the time with a proper OO design.. - Nils
36
[+6] [2010-06-30 01:58:53] stinky472

C++ is basically C with classes.

C++ is much more than that! Is a multi-paradigm language and one that's capable of blending these paradigms harmoniously together to create code that would have been otherwise inferior had we used a single paradigm for the same problem. Skipping more subtle differences (ex: greater type safety, better variable scoping), let's consider just the multi-paradigm aspect.

Let's assume that we're writing a linked list and pretend that no linked list implementation, algorithms, or utilities of any sort to aid us already existed in the standard C++ library or boost.

We decide to use object-oriented techniques and generics and successfully create a list class capable of doing anything one would ever want to do to a linked list: insert elements to it, remove elements from it, and iterate through it.

Now we find that we want to be able to find elements in the list. What do we do?

Given primarily object-oriented techniques at our disposal (only classes), we might be tempted to:

  1. simply add a search function directly to the list class. Yet what happens when we later discover that we also want to reverse the list and do all kinds of things with it? The result will be a monolithic class which goes through endless maintenance and revisions. Moreover, if the list implementation details change, this monolithic list might require a complete rewrite!
  2. inherit from the list to make super list classes with more functions. This is possibly even worse than #1 as it is prone to slicing issues, incorrect downcasting, and so on. It is also just as vulnerable potentially to breaking on rewrites.
  3. Use composition: write a wrapper class which stores the list as a member and provides additional functions to the list. This is far superior to #1 and #2, but requires an interface which duplicates the existing list's functionality. Most people would not choose this approach out of the tedium involved with it.
  4. Do the same at #3 but store a reference/pointer to the list and add the additional functions on top along with an accessor to the original list. This is also far superior to #1 and #2, but requires a lengthier syntax on the client to access the original list's interface.
  5. write a separate class which provides algorithms to act on lists being passed in. This is the best approach given what we have, but it is primarily a procedural approach regardless of whether we choose to put these functions in a separate class. Unfortunately, most people working in languages that are more strictly object-oriented like Java do not apply this solution enough, instead favoring solutions like #1 and #2. Probably the creation of a new class just to hold new functions is counter-intuitive to most people.

In C++, a multi-paradigm language, the best solution is very obvious. Simply write a separate, free function for such auxiliary functions! When we do this, we get all the benefits of #5: no tight-coupling and therefore no vulnerabilities to list rewrites. The implementation could even change from a singly-linked list to a doubly-linked list or even a completely different sequence type, it doesn't matter as long as the public interface doesn't change. Unlike #3/#4 (composition approach), we don't have to duplicate the public interface of the list.

Finally, when we do things this way, we realize with additional paradigms like generic functional programming, that we can even generalize these separate list algorithms to work on a lot more than list types and even accommodate predicate-based searches without any abstraction cost.

Exception-handling is slower than error-handling (even for non-exceptional cases).

This may be the case on certain compiler implementations, but we need fair comparisons! How many times have we seen a real world system of any scale that properly checks for all possible errors (every possible malloc failure, just for one example) that the program can ever encounter and properly propagates them down the call stack manually to the error-handling site? Almost every function in the system would need to do some error handling to do this as thoroughly as exceptions, and we never find this kind of thoroughness in real world projects of any large scale. Of course any ideally-written code to thoroughly deal with all possible errors is going to be slower than code which ignores a lot of errors and doesn't thoroughly handle them.

Exception-handling is optional with C++ and can simply be turned off without side effects.

Consider what happens with std::list<T, Alloc>::push_back when called to insert an object of type Foo. We invoke the copy ctor of Foo when we do this, and it could throw (ex: call to operator new threw std::bad_alloc). Good implementations of the standard library will deal with this case very gracefully, rolling back everything done so far in the push_back as though it were a transaction, yielding a valid list state as though we never inserted anything to the list. Turn off exception-handling and suddenly we have no way to get this kind of robust behavior. It's the same not just for the C++ standard library, but for all kinds of other C++ libraries that use, as an example, operator new (and not the nothrow version) like boost.

C++ hides code more than C.

Short of exception-handling and implicit constructors (which should generally be avoided), this is often not the case. This is a common argument made by people who lack experience using C++. Given a section of code, a novice might have a difficult time telling you where a destructor will be called given non-exceptional execution flow. An experienced C++ programmer would have no problem pointing this out.

C programmers are used to the idea that operators are not functions. C++ programmers are used to this and can easily point out where an operator will be invoking user-defined functionality. One only need look at whether the operands involved are PODs or not.

To the contrary, a lot of C systems hide code a lot more effectively from the programmer than C++. Consider the C preprocessor, for instance. Nothing hides code better than macros, as we cannot even practically trace through the code in a macro with a debugger.

Using directives should be avoided (ex: using namespace std;)

Sutter argues that using directives are what makes namespaces practical, and for good reasons. Without using directives, we have code that's very vulnerable to ADL-related problems. Virtually everyone agrees that argument-dependent lookup is very evil with the way it's inconsistently implemented across compilers, and using directives mitigate that problem far more effectively than, say, using declarations (ex: using std::cout but forgetting to write using std::operator<< or using std::list but forgetting using std::swap).

Inlining one-liners like accessor functions will make them faster.

Wrong and not even close. For all practical purposes, inlining such functions can reduce code bloat (provided the single line requires less instructions than pushing arguments to the stack, calling the function, popping, and returning), but even then inlining all instances of such code can slow things down as it can cause the compiler to try to equally optimize less commonly-executed code branches with ones that are commonly executed (the compiler can't read your mind about the desired runtime behavior of your code). Inlining should always be done only with the aid of a profiler where one can appropriately analyze the most commonly executed branches of code and selectively inline to help the compiler, even for one-liner functions.


37
[+6] [2010-02-11 15:38:14] Nemanja Trifunovic

Myth:

Java, C# and other higher level languages are valid alternatives to C++.

When they are, C++ was probably used for a wrong purpose to begin with. In reality, only languages like C, Ada, Forth are alternatives to C++.


Depends on the application. For example, I was able to generate a GUI application using Java faster than using C++ (I had only a couple months of Java experience). This is because Java comes with more standard libraries than C++. However, I wouldn't use Java on an embedded system. - Thomas Matthews
(8) If you add a couple of libraries, C++ is general purpose and fast. In the right hands, it's alternative to all other programming languages. - Pestilence
(1) So what, you are saying they are invalid alternatives in all cases? If you can do the exact same thing in a language other than C++, and the other language is the one the programmer is more familiar with, then I see no reason why their choice to use the other language is 'invalid'. - Jacob Bellamy
(4) Whether another language is a "valid" alternative to C++ depends on what you're doing. There are plenty of cases where you're going to get better performance out of C++, but there are also plenty of cases where languages like Java or C# will match C++, and they're likely to be much less costly in development time. Java, C#, and many other languages can definitely be valid alternatives to C++. - Jonathan M Davis
It is not abou the speed (OK, sometimes it is) but the purpose. C++ is a system language, and if you were doing typical web or in-house business programs you should better use something like Java instead. For purposes such as system programming, games, image processing, embedded/real-time, etc. C++ does not compete with languages like Java and C#, but the low level ones such as C or Ada. - Nemanja Trifunovic
(2) @Pestilence: Now there's the biggest myth I've seen; the “C++ is my hammer” fallacy. C++ fits some problems great, but others are best tackled in different ways. This is OK and expected; no reason to expect a single tool to be sufficient for everything. (NB, the same applies to every other language too.) - Donal Fellows
(1) @donal-fellows: lol. Every scientific study I've read about language comparisons show the benefits between one another to be statistically insignificant, once you factor in variables like: skill, domain expertise, etc. The cost of retooling an organization or concurrently supporting numerous languages far outweighs the degradation experienced by sticking with a sub-optimal tool. The justification of "best tool for the job" isn't evidence based, because there's so little evidence to support it. Are there exceptions? Yes, but you're more likely to be hit by lightning than confront one. - Pestilence
(1) @Pestilence: I don't trust those studies entirely. C++ is considerably slower to write than some other languages once you factor in expertise level. This is because it is a lower-level language, and it gains execution speed (particularly in the hands of an expert) as compensation for this. For some tasks, that's a very good trade off. For others, C++ is not so good because other languages are able to operate at an abstraction level that is closer to the natural level of the problem. Keeping that small is very valuable as it lets you produce solutions sooner. [TBC] - Donal Fellows
(1) There are a great many problems where the speed of execution isn't a big issue (e.g., because the problem is I/O-bound anyway) and so being able to rapidly develop and deploy correct solutions is more important. However, there is also a middle-road where some parts of the problem are speed-critical and others are not (many GUI apps are like that) and it is in those where there is a huge benefit in writing “heavy-lifting” components in one language (e.g., C, C++, Fortran) and stitching it all together in another (e.g., Lua or Tcl). - Donal Fellows
And the reason I don't trust those studies? It all depends on the exact question asked really. It's the GIGO principle. Conducting a valuable study in anything is really difficult (ask any experimental sociologist) and it's very easy to miss important things. One of the most important things to note is that there's no need to have the same person write the heavy-lifting components and stitch them all together. - Donal Fellows
@donal-fellows: There's a general assumption that C++ is low level. It's capable of low-level operations, but it actually is quite high level. I've been coding with conventions (for years) that have only recently caught on with the introduction of the Boost C++ Libraries and other similar efforts. You can do several amazing high-level tasks without the penalty of traditional high-level primitives. It's all in the hands of the developer. Even with a language regarded as "bad" like PHP, you can still write excellently proper code. Algorithmic deficiency is the biggest problem, not the tool. - Pestilence
@donal-fellows: I swear that C++ is actually more elegant and faster to develop in than many other languages with the supposed "high-level benefit." I still love Python, BTW. I've written log processors in C++ that took less lines of code than well written Perl and could perform recursive matching (impossible in Perl natively). Sure, you need to do some extra lifting, but then that's an issue of the libraries and not the language itself. C++ bolts on, many high-level concepts like generics, that have only recently been adopted by "modern" languages like C#. I don't get the low-level argument. - Pestilence
@donal-fellows: Regarding the studies, there was no particular question being asked. Statisticians simply looked at the raw data and extrapolated actual performance, independent of subjective opinion. When you look at the evidence, languages as progressive as Ruby, which I adore, don't provide the benefits they claim (independent of the developers themselves). Frameworks like Rails help, but that's not a language thing. It's a library and one that's been cloned by almost everyone that reads Fowler's books. - Pestilence
@donal-fellows: I can write similar code in OO, functional, imperative, and declarative languages. I regularly use over 20 distinct computer languages. I've never been hindered by any of them in a way that has prevented me from writing code the way I think it should be written. Yes, Smalltalk tends to be smaller than my C++. It's not enough considering the sacrifices that need to be made. Honestly, I'm not being religious here (C++ or die). I could make the same claims about modern revisions of Pascal or Fortran. They are equally as capable as C++, just not even close to main stream. - Pestilence
(1) @Pestilence: We disagree it seems. To say that frameworks and libraries don't matter is wrong anyway (in fact they matter far more than they should). Moreover, there are a lot of communities where Fortran most certainly is mainstream even now. (Don't know about Pascal.) There are whole realms of applications where C++ simply can't compete (e.g., because it's difficult to strongly sandbox; both Java and C# do strongly there). What's more, generics predate C++'s adoption of templates; they're commonplace in functional languages and have been for at least 2 decades. - Donal Fellows
In short, C++ has lots of stuff in it and learning it is a bit like becoming a Master of Zen. Most people just don't bother; they've found ways to be productive without such an investment of effort. - Donal Fellows
And the studies… I will certainly not credit them at all (well, no further than hearsay) without reading them to see exactly what they really claim. The exact nature of the input data matters a lot, and good data is really not at all easy to come by. I'm also very suspicious of anyone who claims that they have a neutral methodology that makes no assumptions; I suspect that too often what really happens is that they have no idea what they have actually assumed (often that's hidden in the details of the statistical tests they're using or what they've tried to control for). - Donal Fellows
@Nemanja: why did you put Forth in the list ? Is it a matter of "look for the intruder" ? The only common point I can see is that Forth is very compact in size. - kriss
@kriss: I put Forth because it is a low-level language, just like the others I mentioned. - Nemanja Trifunovic
@Namadja: not really. The very simple syntax does not make it low level. It typically works with a very short interpretation loop, but in typical implementations vocabularies are not even compiled to machine instruction. Much more similar to say Java or Perl, than to C. But OK, I you mean a language that can be used to create software for embedded devices with very few memory, Forth is fine, as it's internal code is usually shorter than assembly equivalent. - kriss
38
[+4] [2010-02-11 14:59:38] jalf

Pointers are just memory addresses

  • No they're not. That's why incrementing an int* doesn't advance the pointer 1 byte, but sizeof(int). It's why incrementing a pointer past allocated memory is undefined. The memory address certainly exists. The pointer does not. And of course, an implementation could map pointers to something other than memory addresses if it so chose.

And in a similar vein,

Pointers are just integers

  • No they're not, that's why you can't multiply two pointers. (And of course, on hardware with segmented memory models, even memory addresses aren't just integers either)

Code written in C++ is inherently more efficient than similar code written in any other language.


(78) Pointers ARE just memory addresses. The fact that incrementing them conveniently moves the size of the pointee type does not change that -- it stores an address. - Peter Alexander
(1) No. If you add 1 to the address 0xdeadbeef, you get the next address (0xdeadbef0). If you add 1 to an int pointer you get a pointer to the next int. - jalf
(3) Perhaps you can show me where in the standard it says "pointers are just memory addresses" though. And then please explain to me how it it is possible for a compiler to generate Flash bytecode from C++ source. Memory addresses aren't available in Flash bytecode. - jalf
(3) You might find jalf.dk/blog/2009/07/the-great-pointer-conspiracy worth a read to clear up this misconception. Nowhere in the standard does it say that pointers have anything to do with memory addresses. And the operations defined on pointers have little in common with the operations that are possible on memory addresses. - jalf
(28) I have never worked in a language whose community is more prone to argumentative pedantry than C++... - Greg D
(8) @Greg: True. Then again, I've never seen another language where such pedantry mattered so often as in C++. If you treat pointers as "just memory addresses", you'll barge straight into undefined-behavior land within the first 10 lines of code. - jalf
(1) @Poita_: So tell me then, why does this code invoke undefined behavior? int arr[10]; int* p = arr+11;? There's nothing to prevent me from adding 11 to a memory address. But with pointers it's not allowed -- because pointers are not memory addresses. - jalf
(18) Lemme quote from the Standard about object pointers: "A valid value of an object pointer type represents either the address of a byte in memory or a null pointer value". - Johannes Schaub - litb
(1) To nitpick just a little, it is explicitly well-defined to increment a pointer to one location past the end of allocated memory (but it's still UB if you try to dereference it). This is how some end iterators work, especially for raw arrays. - Tyler McHenry
@jalf, I get your point, but in practise, pointers are definitely memory addresses. Flash bytecode is a special case. - Agnel Kurian
(1) Well, i think Flash doesn't matter. A term used in the C++ Standard is not needed to match the meaning of the term in other areas. For example, the terms "pointer" and "integer" used in the C++ Standard are distinct concepts, while otherwhere, these terms may be interchangable. - Johannes Schaub - litb
(1) @jalf, your responses have not disproven anything I said. As I clearly stated, the fact that pointer arithmetic works in the size of the pointee type does not change the fact that it stores a memory address. All you're proving is that operations on memory addresses are different from standard integer operations, which I never disputed. As for your "invoked undefined behaviour" example, it doesn't invoke undefined behaviour until you actually dereference that pointer, and that's because the memory address that it points to is unallocated, which has nothing to do with what a pointer stores. - Peter Alexander
(4) @Poita_, i think he is right about the undefined behavior of arr+11, because of 5.7/5. It is similar to this one, which also invokes undefined behavior: int a[2][1]; int *p = &a[0][0]; p+2;. Contrast it to this one, which does not invoke undefined behavior (using the same array): p+1+1. The first +1 will point to the second sub-array, to which you then add 1. If you do the addition in one go, you go straight out of bounds of the first sub-array. (note the binding is (p+1)+1). - Johannes Schaub - litb
(2) A pointer value is an address -- but like most values in C or C++, there is (at least potentially) also type information associated with that value, and the associated type determines things like whether and if so how that value can/will be manipulated. - Jerry Coffin
(1) @Jalf: people argue over C++ so much b/c it is arguably the best overall most useful, flexible, and stable language in existence. - Brian T Hannan
(2) C++: Because some people like to have to think carefully. - Paul Nathan
(1) @Poita_: I never said that pointers did not store memory addresses. I said that they are not just memory addresses. They obviously contain a memory address (at least if the compiler targets machine code), but their semantics are different, and more specialized than memory addresses. You can do things with addresses that you cannot do with pointers, and vice versa. - jalf
(2) @litb: yeah, I'm not denying that a pointer represents an address. I'm just saying that it is not the same as an address, in the same way that an int isn't the same as a register. A pointer is an abstraction meant to be mapped to memory addresses by the compiler, but it's still an abstraction with its own rules and semantics that a C++ programmer should respect. - jalf
Pointers hold memory addresses. They may not. - Pavel Radzivilovsky
@jalf: are you saying you never wrote code like int a[10]; int * p = &a[5]; p+2; as I read 5.7/4 int * p should behave like an array of one int in this case or it's behavior is undefined. And it's the simple part, for example I can't make my mind if the following is or is not defined int a[10]; int * p = a; p+2;. Am I transferring the arrayness of a to p or not in this case ? Using pointers and arrays became quite intricated with this pointer are not addresses mindset (and the worst is that no compiler I know care the less of that bullshit). Is the ISO game to break existing code ? - kriss
@kriss, Seems like an oversight in the standard, and that's all. - strager
@strager: I see it as a symptom of a more important design flaw. If you see this as an oversight in the standard how do you believe it could be corrected ? - kriss
39
[+4] [2010-09-26 02:15:45] Xinus

C/C++ is faster than Java in all scenarios


(4) -1 In practice, it always is. - Viktor Sehr
(2) @Viktor: Its not true in all scenarios. The JIT compiler can take advantage of current specific hardware architectures and produce binary accordingly. So long running programs tend to get more optimized than C/C++ executable. More information can be found here stackoverflow.com/questions/1984856/… - Xinus
(4) Why do you say that? They have said that JIT makes programs soo much faster for more than 10 years now. Theoretical this may seem right, but ... When you need performance, you can do very 'low-level' things in C++, which you cannot dream to do in Java. And no JIT compiler will in the immediate future be clever enough to beat that. Nevertheless, you are right with your answer. There are things, where Java can be faster. - Christopher
Specifications can't be faster. However, I wrote a Java thing to plot charts. The first chart took 5 seconds, the second one took 2.5 seconds, the third one approx. 1 second. The same thing in C++ would have given constant time per chart. And considering you can let C++ code compiler and optimize for hours, a fresh compilation will usually be faster than the corresponding Java one. However, that might not always be the case, but in almost all cases I've personally seen. - phresnel
40
[+3] [2010-02-13 02:21:09] Merlyn Morgan-Graham

C++ is faster than garbage collected languages.

This is a generalization that is widely held, and is both logically and empirically wrong. It can be faster, depending on a lot of factors, but isn't always. This is touted to justify pre-mature optimizations (such as picking C++).

Technically, this is an argument about manual memory management (or reference counting) vs. GC, not about C++, but the MYTH is perpetuated in context of C++.

Plus, C++ has general-purpose garbage collection libraries available for it :)

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.26

Note you could expand this into "C++ is faster than higher-level languages," and all of my points can be expanded to match.


Not a myth at all. For a GC language to have a comparable performance with a non-GC one, virtual memory would need to cooperate with the GC. See this (pro-GC) article: lambda-the-ultimate.org/node/2552 - Nemanja Trifunovic
@Nemanja: I read the excerpt. That seems like an interesting article. In my opinion, it is far from solving the debate, because what it describes isn't production manual memory management, it is modelling "God's GC". First point: define manual memory management. You can't, because that could be one or multiple of: stack allocation, deallocate imperatively, via RAII, via reference counting, via memory pools, via program termination. Then there are a lot of GC implementations, with varying trade-offs and optimizations. - Merlyn Morgan-Graham
@Nemanja: I have also seen (sorry, no references right now) claims that GC can be faster than manual management. The statement in my answer is bandied about as common knowledge, unqualified, and without additional research for applicability in the specific scenario. Such use is propagation of a myth. - Merlyn Morgan-Graham
I think they mean that a gc language has a lot of constraints(especially no pointer tricks) which can help a jit compiler a lot, this is not common for a any old programs but I've heard it can happen for long running processes written in java( from what I've read the jvm seems to have the most work done on jit and gc tech). - Roman A. Taycher
Whole sentence is nonsense. Programming language can not be faster nor slower. It depends ONLY ON COMPILER AND MACHINE ARCHITECTURE (including virtual machines) how fast compiled code will run. - doc
The JVM does memory management faster in some cases than C++ manual memory management. For example, create a naive binary tree in both languages (rightLeft = new Node(); leftLeaf = new Node();), create a massive tree, and then delete both. You'll find that both languages perform similarly. Change the new Node() to use boost::object_pool and you'll find that the C++ code now runs much much faster. The truth is that the Java JIT compiler automatically uses memory pooling, while C++ doesn't, so if you're doing manual memory management, you have to do it intelligently, but it is faster. - Brendan Long
@Brendan Long et al.: And that leads to conclusion that which one is faster depends on implementation. GC isn't really a language feature, it's just a pre-implemented memory manager. Of course, Java's GC must track references and that brings some overhead. But what if some machine would have hardware support for garbage collector? In such case Java's GC might be faster than raw C++ memory pool. And the question goes on. - doc
To assume that using memory management systems other than GC is premature optimization is assuming that GC makes things easier. That is a myth! Consider all the manual cleanup one has to do in 'finally' blocks in Java because of the GC. Consider the need for weak references and the number of resource leaks one can introduce by having A store a reference to an image which prevents it from being garbage collected in other parts of the system that think that there are no references left to the image (it only takes A storing a reference to it to make trouble). - stinky472
The only case where people generally agree that GC makes things easier is for dealing with shared resources across multiple threads. Yet GC definitely has its share of migraine-inducing problems to those interested in writing robust applications. - stinky472
In my experience, this myth is usually characterized in terms of performance, not in terms of achieving an elegant design. It is an extremely rare situation when a person can predict perf, or even determine perf without tests and tools. As for your scenarios, depending on your design, they might be just as troublesome in C++ if you're using smart pointers. In either case, you have to deal with proving your system correct. - Merlyn Morgan-Graham
Note I said premature optimization. If you have thought through your scenario and fully understand that you need manual memory management to achieve a simple design, then it is no longer premature :) Remember that the general spirit of myths is that people make blanket statements, causing people to make assumptions. - Merlyn Morgan-Graham
41
[+3] [2010-02-24 13:06:59] Goz

1) That you know exactly what the C++ compiler is doing. Lets face it very few people do and, even though I've been writing assembler for nigh on 15 years and have a better understanding than most of what the compiler is doing under the hood, I'm STILL amazed at some of the choices a compiler makes (good and bad).

2) That a number with a ".[n]" is a float. I've had so many problems on platforms without doubles with this one. Its amazing how slow a software double to float conversion is. please remember the 'f' on the end!

3) The NIH syndrome. OK I accept this isn't juts down to C++ programmers but I've found it more with C++ programmers than anywhere else. Its fine to use someone else's code. Just make sure you use code that comes recommended or from a reputable source. Nowt worse than relying on buggy code :(


On platforms that do have double, it's very common for all arithmetic to be done in double or extended precision, and so there's no efficiency advantage to using float. - dan04
@Dan: Thats not true. There is ALWAYS an efficiency advantage in well optimised code. Often you won't notice the memory bandwidth savings because the latency is hidden by other things. Well pipelined and optimised single precision code will ALWAYS be faster than double precision code as a result of this throughput. Add to that I've never come across a processor that is quicker processing double precision than single precision (x86 is significantly faster with single precision, for one). - Goz
42
[+3] [2010-03-09 23:33:04] doc

C++ is no longer a modern language

Actually it is syntactically most powerful imperative language.

C++ memory management model is old and inconvenient

Java was so proud to have garbage collector. In larger projects it ended up with explicit calls of methods like .dispose() (in SWT for example) and a lot of troubles with threads. In C++ you have a choice (do it manually, use memory pools, smart pointers, garbage collectors).

Arrays are evil, you should always use STL containers instead

I'm falling to pieces, when I see people using std::vector for plain arrays with known size and no other functionality than subscript access, often without forward space reservation, calling push_back(), push_back(), push_back()....

Inheritance brings some performance overhead

No it doesn't unless method is not virtual and it is not called in aid of base class.


"C++ is no more modern language": The syntax of that and the following sentence needs some attention. I'd fix it for you if I knew what it meant. - Clifford
(2) @Clifford: Maybe it should be written in this fashion "C++ is modern language no more" - in other words: it is believed that C++ is obsolete. In my native language it is allowed to swap such phrases, so maybe I made a mistake. Sorry for that. - doc
I think you mean "no longer" rather than "no more". "no more" can mean "no longer", but it can also mean "not greater than", so is perhaps ambiguous. I hope you are not offended by my edit. I am impressed that anyone should even attempt to write in a non-native language! - Clifford
No problem Clifford, feel free to edit my post. "No longer" is what I meant. - doc
@doc: for the "syntactically most powerful imperative language" nobody that ever used python, ruby or perl could agree... maybe if you word it "syntactically most powerful compiler oriented imperative language" I would disagree less (as there is not many other candidates for the ecological niche of compiler oriented language). - kriss
@kriss: Sometimes it's hard to compare statically typed language with dynamically typed languages. For example, Perl, Python or Ruby are not applicable to support templates (or generics in non-C++ world), function overloading, static polymorphism, typedefs etc. Static typing brings whole set of language features that can be utilized. Of course you may not need them, but sometimes they are strongly desired. - doc
@doc: OK, it's hard to compare. But what you can do using template can be done with better macros support in other languages like Clisp, or even more builtin within languages in say Haskell, other OO languages allow for metaprogramming, what C++ can't do, etc. In the end we are left with C++ is the best C++ around (well, I would say second best after C++0x, but it's probably the same thing). - kriss
@kriss: Haskell and Lisp(s) are not imperative :) ;) - doc
(1) @kriss: C++ can be compared to Java, Pascal/Delphi, C#, D, Fortran, Visual Basic... Some of them are said to be more "modern" than oldy C++. That's what I was about. - doc
@doc: 'imperative' is a meaningless restriction here, an even smaller difference than compiled vs dynamic (and you can use imperative style with CLisp, as you can write recursive program in C or C++). But OK, I get your point there is worse horses around ;-), and C++ is still evolving. Never heard anyone say that Fortran or VB were more modern than C++; compare C++ with D would need a full discussion but it's clearly not the choice of the market. Java and C# also have some very interesting points and really comparing them with C++ give no obvious winner. - kriss
Statically typed languages, by definition are 'syntactically less powerful', the syntax is restricted in such a way that a lexical analysis can prove (not decide) the absence of a lot of annoying errors. Therefore, the syntax is less powerful. That's about the only definition of 'powerful syntax', I can think of. - Lajla
@Lajla I don't know how you come to such conclusion. In fact, those additional rules provide more sophisticated grammar. Take a look at simple macro processor - it doesn't care much of what's inside brackets. Is it syntactically powerful? By powerful syntax I mean how many mechanisms you can utilize, beside rating them. - doc
43
[+3] [2010-02-11 15:20:15] phaedrus

The whole software has to be written in C++. (No, only the optimized parts need to be written in C++).


(2) interfacing with C++ is hard... you need to expose C-style global functions. - Hassan Syed
(4) @Hassan: A common pattern is to create a C++ application and embed another language in to it - Lua, Ruby, Python, ECMAScript etc. are all common. This can be done without the use of C-style functions. - Joe Gauterin
(1) @Joe Agreed :D I meant only the case when linking against a C++ DLL. - Hassan Syed
(1) Actually, nothing needs to be written in C++, unless you have some C++ library that you need the C++ compiler name mangler to mate up with. - T.E.D.
@TED: int __Foo_Bar_baz__i_s9__Foo_Bar_p_cp(struct __Foo_Bar, void*, char*); (or whatever format it was compiled with; you get the idea) - David X
44
[+3] [2010-02-11 19:26:21] Pestilence

C++ is low-level and requires more time to code

Low-level coding in C++ is optional. One look at the Boost C++ Libraries [1] and you'll quickly see that C++ is capable of some very high-level constructs, without performance penalty. C++ is unique in that it "rides the fence" and provides the best of both worlds.

Many concerns with the language can be mitigated simply by taking advantage of a library or two. You can use garbage collection [2], if you like. Add SOCI [3] and you have safe database access with a syntax that cannot be beat in any other mainstream language.

Give a competent coder any project and they can build it just as quickly in C++ as anything else... given the proper libraries and expertise.

[1] http://www.boost.org/
[2] http://sourceforge.net/projects/bdwgc/
[3] http://soci.sourceforge.net/

(7) Any project? Anything else? Can C++ match Perl for text and filesystem manipulation tasks? Can C++ rival ML or Haskell in a domain like theorem-proving or compiler implementation? Can you write an interpreter in C++ as simply as you can in Common Lisp? Can you make a C++ OS kernel as small as a C one? Just because C++ is very flexible doesn't mean it's equally useful for all jobs. - Nate C-K
(3) That's like saying because BF is turing-complete, any developer can make any project in it as easy as in any other language - Earlz
(3) My main point in that statement was to address the idea that writing C++ is time consuming. You're speaking of simplicity, elegance and binary code size. I wasn't evangelizing a golden hammer. I believe in using the right tool for the job. What I don't believe in is pigeonholing tools. "Perl is only for text processing." "You must use Java for middleware." "C++ is only for low-level stuff." "Kernel development must be in C99" C++ does excel in many other languages' domain of expertise. If you're building a log processor, Perl isn't necessarily the best choice... nor is C for daemons. - Pestilence
Comparing C++ to BF? That's low down. - Pestilence
Kernels in C99? Where'd you find that? Most kernels are written in C89. Linux is written in C89+GNU extensions. I think even more kernels are written in C++ than in C99. Microsoft doesn't even have a C99 compiler. - jbcreix
Yeah... Linux = C89 + gcc hacks + C99 features, like designated initializers. C89 sprinkled with C99 back-porting. Not exactly pure C89 nor C99. Sorry I wasn't more specific, as I don't think anyone's fully implemented C99 yet. - Pestilence
C++ is low-level and does require more time to code. Python: print 'Hello, world' Ruby: print 'Hello, world' Lua: print('Hello, world') C++: #include<iostream> int main() { cout << "Hello, world"; return 0; } QED. - Imagist
(7) @Imagist: proofs and demonstrations aren't really your strong point, are they? :D - rpg
@rpg If you have something to say about why my proof is invalid, say it. Self-congratulatory remarks neither refute my point nor contribute to the discussion in any way. - Imagist
In my 20+ years of programming experience, projects based in C++ do take longer to complete then projects done in higher level languages such as Java, VB, Smalltalk, etc. This is a gross generalization, and the statement may be misunderstood by the person making the statement, but the generalization is still fundamentally a true one. - Mordachai
(2) @imagist, Your example, if written in Java, is even larger. - Pestilence
(4) @mordachai, Two years ago, I'd have agreed with you. I really believe that C++'s biggest weakness is the lack of a decent standard library. STL doesn't even have a hash map, but that's not the language's fault. If you stick with the raw / default toolset, then you're slumming it for sure. C is all about including and linking. With powerful containers, versatile algorithms and components modeled after usable design patterns... you can achieve an assload of productivity in this language. - Pestilence
(1) @Pestilence I think you have not coded much using Java IDEs. A refactoring task of a large codebase in C++ takes forever compared to in Java. Overall, C++ is surely lower-level than java. - phaedrus
(1) @Pestilence True, for that one specific example, but in most cases Java code is shorter. And it's nearly always higher level. But even if I were to concede Java, there's no arguing that C++ is lower-level than most languages and takes a comparatively long time to code. - Imagist
@Pestilence Just to clarify, calling C++ low-level isn't an insult. C++'s low-level nature is what makes it uniquely suitable for some tasks (and inappropriate for others). The fact that it takes longer to code is a necessary evil to accommodate its low-level features. I am not hating on C++. But I really despise language advocacy. Language choice is always a series of trade-offs and it benefits nobody to pretend that there aren't both positives and negatives to any language. - Imagist
(1) @Imagist: I feel your point is valid but the example you chose is extremely bad. - missingfaktor
(2) Weakest part of C++ is something that we call module, package or extension systems in other languages. C++ offers here prehistoric "include" directive + linker arguments to link with libraries. Even lack of standard library wouldn't be a problem, if you could just download a package, import it into your project and distribute with your app. - doc
Yes. Linking libraries in C++ is terrible compared to everything else, other than assembly. +1 - Pestilence
45
[+3] [2010-02-11 21:20:12] Sylvestre Equy

Who's your audience? If you want to convince higher-level developers (as in higher abstraction) to learn C++, you should not go straight to C++ intricacies. In a very subjective way, I'm sure C++ is a fantastic language in its possibilities of fine grain tuning, though, as a C# developer, I'm still reluctant to go C++. I'd be delighted to be convinced that the productivity/performance ratio of C++ is higher than C# or Java or (your favorite high level language) ratio. Anyway, good luck for your article.


Yes, sure C++ is not for every programming task. Sadly many people (still) make it to be so. They forget to understand that with programmer productivity you also loose the opportunity for program optimization. - phaedrus
46
[+2] [2010-02-11 15:16:19] RC.
  • STL Containers are guaranteed to be thread safe even for reading by multiple threads
    • (NB: many implementations do specifically guarantee this, including STLPort [1].)
  • Template coding causes code bloat
[1] http://www.stlport.org/doc/sgi_stl.html

(4) Did you mean reading and writing by multiple threads? I think for reading by multiple threads pretty much everything is "thread-safe". - Dmitry
No it isn't, in fact. Single thread writing, multiple threads reading is NOT safe. A reading thread may see an inconsistent interim state. - MSalters
(1) Even having multiple threads reading (without any writes) is not guaranteed to be safe. The key word here is guaranteed. The C++ standard does not address multi-threading and thus thread safety is implementation specific. - RC.
(1) @RC: it's not hard to find an implementation of the STL which is thread-safe for reading: stlport.org/doc/sgi_stl.html @Dmitry: grep your STL for mutable. - Potatoswatter
Yes, I realize that it is supported by most implementations of the STL. The myth is that it is guaranteed by the language b/c you're only reading and not modifying. It's not. - RC.
(1) STLPort is an implementation of the STL, but most library implementations that people use are in fact implementations of the C++ Standard Library, a distinct entity. - Lightness Races in Orbit
47
[+2] [2010-05-19 16:38:45] kriss

C++ is a better C

While there is great features in C++ and C is nearly a subset of C++, the base design choices are very differents. C++ is a quite high level OO programming language, even if very compiler oriented (which explains why you miss features like metaclasses but have templates). On the other side, C was born as a kind of quite low level portable assembly language.

Today as a low-level programmer I miss a really low-level language that would be object-oriented and replace C, I use C++ for such purposes but I do not believe it's C++ (there is probably one such language around I don't know of, may be go, but I'm still unsure).

A point that is largely overlooked with C vs C++ is that a C compiler is quite easy to write, while a C++ one is much more complex. When you are working really low level (think of automated parallelizers for GPU, compilers to silicium or such things) you may want to write a compiler to experiment (first hand experience, some times ago while in PHd I did it to try some features of an experimental superscalar processor). C++ is much too complex a target for such needs. The usual target is C, too bad there is no available simple OO target and you have to either stick with procedural paradigm or simulate OO programming using C.

I remember the days when C++ was a preprocessor for C and mourn of what was lost making it a language.


Downvote without bothering to comment ? I take it as proof enough that this myth really hold :-) - kriss
@kriss: First wasn't me, but -1 from me. C++ isn't just an OO language, and doesn't even fully embrace it like other languages (such as C#). I cannot think of a scenario where C would be used over C++, given the choice. - GMan
@GMAN: you say it given the choice the main problem is that C++ compilers are orders of magnitude more complex to write than C compilers. Really there is many uses case where you can't even have a full C compiler but must work with a restricted one. Think of embedded systems, of compiling to ASICs, of real time systems, etc. One example: using C it is easy to forbid malloc, it is just a library call. Harder to remove new, delete and object instanciation from C++ : it's in the language. The main point is that C++ is not KISS while C is. A good low-level language should be KISS. - kriss
If some other C++ religious people care to downvote, I will gladly remove this post (no need to speak to someone that can't hear) and get a badge. - kriss
Of course I say given a choice. Without a choice, C v C++ is meaningless. Given the choice, C++ can do everything C can, but is much more expressive and safe. It's just as easy to forbid calls to memory allocations in C++ as in C. But object instantiation? I don't see any program getting far without that... I agree, C is a simpler language but that comes at a price: it's very messy when you actually get to coding. C++ is more complex language, but far easier to code with. I don't know, I don't see any of points as valid. A bit more concrete might help make your point. - GMan
@GMan: I updated my answer as you may have seen. But you can't really catch what I'm meaning if you don't walk in the shoes of a compiler writer. What upset me with C++ vs C is that you should be able to get all of what C++ have to offer with a much simpler language. Ability to call existing C code should be enough, no need to program in C inside another language. The problem is that doing that C++ took an ecological niche (low level programming) for which it is poorly fitted because it simply embrace too much. - kriss
@GMan: I can explain it another way, maybe simpler. Another poster explained that C++ is easier to understand if you see it as 4 different languages: old C preprocessor, old C, OOP and templates. The problem is exactly the same that mixing up different parts of a system in the same class. We could have a well defined layered language with 4 expressive and simple languages (maybe just 3 as template and preprocessor could probably merge, but other layers could also be added)... instead of that we have C++. - kriss
I also did not downvote this. However, in response to GMan, there are cases where I would choose C over C++. It would be for small-scale projects (e.g., on an embedded system), where I might need something like implicit pointer casts for convenience. That would be downright evil behavior to C++ programmers, but this would be the kind of application that needs to be evil to be written in a practical amount of time and meet the requirements. - stinky472
@stinky: Choosing an entire language because you're too lazy to type (T*) or static_cast<T*> seems awful wrong to me. :S That literally takes 1 second to type, and you're giving up an entire language! - GMan
@GMan: but why bother dropping a bunch of features you never use and don't want to ? And for embeded systems there are also chances no C++ compiler is available anyway... - kriss
@kriss: Then like I've said, the question of C++ v C is meaningless since you can't even choose C++. And if you don't want the features don't pick C. I don't see why you wouldn't want them. - GMan
@GMan: It's a whole a nothing matter. There is many very good things in C++, but some are horrible. One problem is that many C++ programmers will probably disagree about what is good and what is horrible. If you want to avoid the horrible part, you also have to drop the good. On my list of horrible things I have iterators design, no proper module concept (still stuck with the old C include), still no alternative to #define to get values from compile toolchain to source code, plus many obscure or inconsistent syntaxic choice... - kriss
@GMan: to say it otherwise when I use C, when I use python, or when I use Haskell I have a feeling of a consistent languages, with a strong feeling of design behind the language. When using C++, I don't get that feeling, but that of something quite organic that have grown in different directions. I can consider dropping the entire C++ language to use another one more consistent, even if less rich, or more constrained. The best way would obviously be to have a well designed language with the C++ good parts, but it becomes harder and harder while keeping historic compatibility. - kriss
@kriss: But none of those things has to do with C versus C++, those are red herrings. Rather, those are arguments against C. That's fine, but if you're going to argue C++ isn't preferred over C please stick to that argument. Trust me, there's many things I'd love to change about C++ (leaving us closer to D), but I'd still say it's an improvement over the things we have to write with C. As far as I can tell, any argument you have is "I feel like C is a more solid language". That's fine for how you feel, it doesn't somehow take away that C++, while a more complex language, allows easier coding. - GMan
My stance on C v C++ v D. I think our disagreement is I want productivity and you want simplicity. - GMan
@GMan: Yes, that's more or less what I feel. And I agree with you that some features in C++ are much much better than what C has to offer. That's why I currently write software using C++ not C. I did +1 on your answer C v C++ v D. - kriss
@GMan: but I wouldn't speak of productivity vs simplicity, because sometimes the C++ way of doing things becomes so tortuous it consumes days to figure out how to do things. And sometimes I do not even succeed. For example :this question stackoverflow.com/questions/2638654/…. It looked something simple at start, but I never succeeded making it work, as I didn't had a week to work on that, I finally just stuck with C method even if it's not as confortable. - kriss
@kriss: (Funny, I up-voted that question oh-so-long ago. :) ) Hm, is the top-voted answer not satisfactory? - GMan
@GMan: it was the best available, and theoretically was a solution, but I never figured out how to make it work in real code. And also it's still much too complex. The real best answer seems for me is in comments (but as it is comments I couldn't vote for it). - kriss
48
[+1] [2010-08-01 13:38:30] Calvin1602

Const accessors are faster

It depends, but usually no


Usually yes, actually, if your sample pool is "all types". Only a tiny handful of types can negligibly be passed around by value (the primitives); the vast majority of the infinite rest of them will be complex, and are best returned by reference (which is presumably what you meant to write). - Lightness Races in Orbit
49
[+1] [2010-03-20 05:15:28] Permaquid

You should only delete a pointer if it is not null.

Even in a destructor in which the only things being done are deleting pointers that are mebers, it is important to set each deleted pointer to null after deleting it.

memset is a good, efficient and valid way to iitialize classes and structs to an initial default zero state.

The order of initialization of members can be controlled by the order in an initializer list.

Interior classes are a nice way to keep related concepts together.

Varargs are still the best approach to output streams.

If you know C, you can easily pick up C++.


You should rephrase your post stating that the above sentences are myths. It is not that clear. Indeed nearly all of the above is false but hold true by some beginners... (by the way you don't delete a pointer, you delete an instance of the pointed object). Indeed setting pointer content to NULL after deletion and checking if it's not NULL before accessing it is just a bad beginner practice that usually replace segfaults by memory leaks... not much better, probably worse in the long run. - kriss
(3) You're joking, right? - Permaquid
50
[+1] [2010-09-04 17:18:33] zr.

i++ is always as fast as ++i


indeed a myth, but you should have explained more, and what's the assembly difference and in which cases it occurs. - Pavel Radzivilovsky
(3) The funny thing is that the truth has changed many times on this subject. First, when the machines were slow and compilers were dumb, ++i was faster than i++. The Verb was: "Thou shall always use ++i!". Then compilers became smart, and recognized when the return value wasn't used, so what was the Verb became a myth, and now the Truth was "Thou shall use whatever you like more!". Then iterators were born, and what was labelled as a myth, became the Verb again. - Matteo Italia
51
[+1] [2010-09-09 19:48:42] StackedCrooked
  • delete 0 will crash the program (wrong)
  • pure virtual methods cannot have an implementation (wrong, if you don't believe me test it)
  • C++ code is always faster (not if you suck)
  • most C++ codebases are full of leaks (perhaps true, but its easily prevented with scope bound resource management)
  • C++ is dying (it's alive and kicking)

(3) "pure virtual methods cannot have an implementation (not true)" Hey?! Either a method is virtual with a default implementation or it is pure virtual. How can it be in between? - Konrad
(1) @Konrad, in C++ pure virtual simply means that the subclass must implement an override. - StackedCrooked
which is achieved by having =0 instead of {implementation}...? - Pavel Radzivilovsky
@Pavel, yes you must write the =0 in order to make the method pure virtual. However, you can still add an implementation to that method also. - StackedCrooked
52
[+1] [2010-02-11 20:46:33] Kristopher Johnson

Mangled names make it impossible to link C++ code with non-C++ code.

Truth: "Mangled names" are an implementation detail, not part of the C++ language. If your implementation makes it difficult to link C++ and non-C++ code, blame your implementation, not the language.


(5) Maybe I should just go ahead and edit this, but extern "C" would be a useful tidbit for anyone in this situation. I don't think any implementation doesn't perform name mangling; it's as good as required if you don't want restrictions on exporting overloads. That said, more OO languages interface with C++'s object model than any other. - Potatoswatter
53
[-1] [2010-04-07 07:32:25] Asgeir S. Nilsen

Myth: Since C++ is a standard it's the same everywhere

Fact: What C++ is in your environment depend on which compiler vendor and standard library you use. What compiles and runs fine in one setup might not compile or behave differently if you change some of these.


Well, this depends. I routinely port C++ projects from Windows to Linux. - community_owned
(5) C++ is same everywhere. It's a compiler that may not stick to the standard. - doc
Not only the compiler. The C++ standard library is also part of the equation. In addition to the one provided by your compiler vendor you also have STLport, GNU libstdc++, Apache stdcxx, and Dinkumware, among others. - Asgeir S. Nilsen
@doc: standard is paper, compiler is the real thing. The standard by itself won't execute the code, and (as any standard) has some ambiguities anyway. Another point in that in the standard many behavior are 'undefined'. - kriss
@Neil Butterworth: I guess the trouble you have there is at stuff not sanctioned into the standard. - phresnel
54
[-1] [2010-02-14 13:54:27] den bardadym

TR1 is part of standard C++

TR1 is a part of C++0x and it hasn't accepted yet. New MSVS and GNU GCC has particaly this extension.

Also you can use Boost library.

It is faster to use iterators to access a vector than operator[]

It depends on implementation of Standart Library

The C++ Standard contains something called the STL

Stl appears in HP and it wasn't part of standart library. Then stl became part of Standart Library of C++. But standart library also has streams, CRT, algorithms.

I very often use this name when i mean using vectors, stacks, etc.


-1 except for std::vector, it IS faster to use iterators than operator[]. It would be a very querky implemention of deque, set and map which is as fast with operator[] than iterators. - Viktor Sehr
No it did not become part of the standard library. Parts of the stdlib were based on parts of the STL; that is all. - Lightness Races in Orbit
55
[-1] [2010-05-19 17:17:01] chapluck

C++ programmers are more round-shouldered than other


(1) Yeah, may be a voted down is right: "C++ programmers are more fit and neat" is more common myth - chapluck
56
[-2] [2010-02-12 17:52:06] Tronic

Code using operator[] on std::vector instead of .at() runs faster (the latter does bounds checking). The truth: most often the compiler optimizes away any unnecessary bounds checking, making .at() just as fast. Only if the compiler cannot determine whether the index is going to be in bounds, it will keep the check.

Of course you might not get that optimization if your compiler does not optimize well or you haven't enabled optimizations.


How is the compiler going to determine this? - community_owned
Uhm no, as the compiler dont know the actual size of the vector, the bounds checking cant be optimized away. (ie giving the index compile-time doenst mean the compiler can optimize the bounds check away...) - Viktor Sehr
Try it and see. In many cases the compiler actually can determine this. I have ran my benchmarks, have you? - Tronic
@Tronic Please post the benchmark code. - community_owned
(4) You do realize the compiler will inline the calls yes? This also means it was see the bounds check always returns inside, so it eliminates that as well. In fact, all three should produce the same assembly, with optimizations. - GMan
57
[-6] [2010-04-15 19:52:01] alpheus

Myth: C++ (and C, for that matter) has macros.

Sure, these languages have things they call macros, but these things are really just text-substitutions, which can get pretty hairy and complicated.

I am currently learning Lisp, and what convinced me to do so was learning about Lisp macros: things that mold the language to what you need it to do. Of course, they can be hairy and complicated as well, but they can do a whole lot more than C/C++ "macros".

Theoretically, C++ templates help somewhat, but those are hairy and complicated things attempting to alter a hairy and complicated language. In comparison to Lisp, which is (from what I've been able to do so far) a simple, beautiful language, that has archaic, hairy and complicated ways to do things that can be done more easily in more modern languages.

In any case, Lisp has real macros, and C/C++ doesn't.


(5) "§16.3 Macro replacement.", ergo C++ has macro's. A macro, by definition, only has to be capable of text-substitution. This post is a prime example of the "No True Scotsman" fallacy. Nowhere in the definition of macro does it say "capable of all the things Lisp is capable of". - GMan
I'm really just quibbling over semantics: I realize that a single term can mean different things, even in the same language. Having said that, now that I'm familiar with the power of Lisp macros (even if I'm not yet skilled enough to use them) I'm still going to make the claim that C/C++ don't have real macros :-). - alpheus
(3) That's still a fallacy. :) (I agree the Lisp system is much more expressive, but the argument simply doesn't hold. And I'm a pedant kinda guy. :)) - GMan
If you want to argue that it's a Common Lisp myth that its macros aren't better than C or C++'s, go ahead. They're both macro systems, it's just that one is incredibly more powerful and useful. - David Thornley
Yeah ((Lisp (is (beautiful), ((unless you) (are) ((not (one (bracket() too)))))) far) - doc
@alphaeus: +1: I totally agree, C/C++ has a crippled kind of macros and templates are not much of a progress. But the question of the OP is a trap, expressing disbelief in dogma of C++ true believers can't lead anywhere else than downvotes... you should get them as confirmation that you have a good point. - kriss
In effect, lisp macros are abuse of the term macro. C macros can be applied by a preprocessor and don't need parsing and loading of data, before read time. Lisp macros are not lexical, they're structural, they already perform runtime-like behaviour. And Scheme's Syntax-case can even infer to some extend the type of an expression it operates, that's not a 'macro', that's compilation, simply compilation to the same language. - Lajla
I sort-of agree with Lajila's comment: I've been trying to think of a better name than "macro", but so far, I haven't had luck...which is yet another reason why I lose in the "semantics war"! - alpheus
-1, the C Preprocessor (with GCC at least) does have macros and here are two examples of them being used to extend the syntax of the language. - Joe D
Even if all terms used in C++ would be wrong before the Holy Ivory Tower of Information Sciences, they are C++ parlance among C++ programmers and therefore not wrong within C++. - phresnel
58
[-9] [2010-02-11 14:57:17] Greg D

Pre-incrementing an iterator performs significantly better than post-incrementing an iterator on modern compilers.


(48) Depending on the iterator, it often does. - Peter Alexander
Thx for pointing that out! Also discussed at velocityreviews.com/forums/t318572-post-and-pre-increment.html - mre
but not for 'int i' in a for loop - Martin Beckett
(7) This one is actually true in some cases. Postfix increment really means "copy and increment", the copy is often unnecessary and can be avoided by using the prefix increment notation. - ceretullis
@"Martin Beckett": correct prefix/postfix have no performance impact on intrinsic types because the cost of the copy is negligible. - ceretullis
(3) for intrinsic types, often there is no copy. it will simply place the INC instruction in the machine code after the rest of the statement. it can't do that for objects that overload the operator. - rmeador
(2) I support the notion that if you don't need to post-increment, you should do a pre even when it doesn't make a difference. I say this b/c I want devs to take notice when something is post-incremented and ask why. Who knows when that object you're incrementing gets refactored into some other type where now that post-increment makes a difference? Who's going to go back to find and change all of them? Tell the compiler and the other devs on the team exactly what you need as clearly as possible. - RC.
@RC: How often has the pre- vs post-increment been the make-or-break performance killer in your application? - Greg D
(2) -1: This is often true for non-trivial iterators. - Joe Gauterin
(2) @Greg: Does it matter if sometimes or even most of the time prefix increment isn't any faster? Why prefer postfix when there's the possibility that it may be slower? Is it that some people just like the look of "i++" so much better than "++i" that they're willing to possibly sacrifice some performance even if it's miniscule? Bottom line is this: if a programmer is going to prefer one over the other he/she should prefer prefix. - Dan Moulding
I simply prefer focusing on performance in places where it matters. Measure, measure, measure, and I have never seen myself, nor met someone else, who fixed a single performance issue by changing a post-increment to a pre-increment. Pragmatism over all. Could such a situation exist? Theoretically yes. Is it something worth getting bent out of shape over? Absolutely not. In the vast, vast majority of cases, it is irrelevant or optimized into irrelevance. - Greg D
(1) @Greg: Fair enough, but let me ask you this: given that you have a choice between using one or the other in most situations (save those cases where which one you choose actually does matter) what good reason do you have for choosing postfix? - Dan Moulding
@Dan - because the time the next programmer spends debugging a for loop that runs from -1 to 'n-1' because the prev programmer used ++i is rather larger than the 0.1ms the compiler will take to generate exactly the same code. - Martin Beckett
The urban myth is "always performs better". Fact is "often performs better". - MSalters
(4) @Martin: if your maintenance programmer makes that mistake with pre-increment, then there are bigger problems with the code. A for loop index is incremented in the third part of the statement - it does not have to start at -1 just so that pre-increment can be used. Sounds like the loop is for (int i = -1; i < n-1;) doit(++i);, which is stupid anyway. You've successfully argued that badly-written, confusing loops can sometimes be less confusing using post-increment. That's fair enough, but it is not what was asked for, which is any kind of reason to favour post-increment as a rule of thumb. - Steve Jessop
@Steve - ok poorexample, but writing 'unusual' code n order to gain some imagined speed advantage for ++i over i++ are bad. - Martin Beckett
(7) @Martin: of course, if someone can make their code simpler and clearer by using post-increment then they should. But what you often see is i++ on its own as a statement or a loop increment expression. When questioned why they do this, people tend to say either "++i is harder to read", which to me strains belief in their competence, or else "++i is premature optimisation". That sounds to me as though they don't want to be seen to be prematurely optimising, and hence are prematurely pessimising instead, i.e. writing the code they believe to be slower. - Steve Jessop
(6) As others have said, the post increment requires a copy. Particularly in the case of on overloaded class operator, this can be extremely expensive. And to all of those who are claiming premature optimization, this is a trivial change most of the time. Good habits are not premature optimization. - Joel
@Dan Moulding: The productivity I lose hearing older, senior developers complaining two cubicles over because a pre-increment was used instead of a post-increment they're accustomed to more than makes up for any small, rare perf impact. (And, to be fair, I've actually been pre-incrementing my own loops for the last 8 years or so. I'm just saying that claiming it's some kind of "big deal" is a total myth. It isn't. In the vast majority of cases, the perf difference between the two is utterly inconsequential.) - Greg D
+1: I think a discussion of preinc and post inc is a good thing. - Paul Nathan
Using pre-increment where it doesn't matter which is a good habit to get into. It never costs you anything, and in the case of overloaded operators, you gain efficiency. It's just that for some reason, the average programmer is used to using post-increment all the time. Granted, it's by no means a large efficiency gain in most cases (and for primitives, it isn't one at all), but just using pre-increment unless you have to use post-increment will gain you efficiency at effectively no cost. It's not worth obsessing over, but it's definitely a good habit to get into. - Jonathan M Davis
Postincrement is and always will be potentially slower (only an optimization performed by the compiler can avoid it). Go read your Scott Meyers and educate yourself. - Mordachai
I've read the comments and don't understand why people defend for (int i = 0; i < N; i++) over for (int i = 0; i < N; ++i); yes, Martin Beckett, I'm looking at you. edit: @Greg D's comment is a defense I can understand. ;) - just somebody
(1) +1 because iterators are often implemented in header files, in which case the compiler can in fact do quite amazing optimizations. - Tronic
I didn't downvote this as it has already been downvoted plenty, but as pointed out, pre-incrementing an iterator can definitely be significantly faster than post-decrementing it, and that's true even when RVO is applied to eliminate the temporary copying (we still have to create the temporary in the postfix version). Personally I don't see the reason to mix styles. ++it or ++counter_variable. Why make it difficult on yourself by making exceptions to the rule for PODs that shouldn't be applied to iterators? You can use one operator for both cases: no headaches involved. - stinky472
Once you find that the prefix version has many cases where it does outperform the postfix version even on optimizing compilers that apply RVO, the only reason I can think of is stubbornness that someone would use i++ over ++i in code such as the above. One style is easier to learn and is as fast or faster for all cases: that's way simpler. - stinky472
@stinky472: Did you even read the massive stream of comments on this? - Greg D
I never understood why ++i is less readable than i++. They are actually both non-intuitive, and have not even a counterpart in maths or other real lifes ... - phresnel
59