r/cpp • • Aug 20 '12

Does anyone else prefer older C++ code (1998-2003?)

I've been a C programmer for a very very long time. I know some C++ as well, but when I write C++ i tend to keep it very simple. My C++ is more of a C with classes/objects. Two excellent examples of this style of C++ code are the FLTK widget library and the FOX toolkit. Both are GUI libraries that have extremely readable and understandable code bases.

I feel like everyone else is on this modern C++ kick, but I just don't get it. Here are two big reasons I prefer the older C++ code.

  • It's much easier to read the older code (at least for me). This also makes it easier to get new programmers integrated into our existing code base.

  • It works on the compilers we already have. No need to get Visual Studio 2012 or the latest gcc just to compile code that already compiles and works. It even works in Visual C++ 6.0. That's just awesome if you ask me.

Does anyone else feel this way?

12 Upvotes

89 comments sorted by

26

u/klusark Aug 20 '12

What I think you probably don't like is just the overuse of template metaprogramming. Features like auto, nullptr or the new for syntax stuff just help clean the language a little bit.

With your second point about old compilers, I'm the kind of person who uses the latest and greatest as soon as possible so I don't think that point is too important, at least for me.

1

u/aninteger Aug 20 '12

You're definitely correct here. I try to avoid a lot of the template metaprogramming stuff. The more complicated stuff is practically unreadable to me. I'm sure the majority of the STL is unreadable as well (to me).

4

u/[deleted] Aug 22 '12

A lot of this is getting to know and becoming familiar with the idioms. One of the most commonly employed techniques in C++ template metaprogramming is reliance on SFINAE. Recognizing when this pattern is used is one of the keys to understanding a lot of common idioms.

But rest assured: It is possible to go from practically no understanding of the more complex C++ code to a fairly thorough understanding. It is humanly possible, and it doesn't require much more than a healthy sense of curiosity.

4

u/jokoon Aug 20 '12

I really don't understand how template meta-programming can be an productive way of coding. I can't think of where you can need it other than containers.

I agree with the OP, but I admit that using the STL is preferable to using arrays or other stuff.

But it's true, C++ allows you to organize your code a little bit, and C++ is not only about OOP, there's also a lot of other nice features which makes C.

I agree than C++ don't make me change my habits of how I'd code things in C, procedural programming is simple enough for me, and that's how I do things.

25

u/WalterBright Aug 20 '12

The point of template metaprogramming is to be able to write generic, reusable components that will compile to the efficiency of hand-coded, custom versions.

2

u/StackedCrooked Aug 21 '12

And to impress your colleagues.

1

u/rbv Aug 20 '12

That's not metaprogramming. Just straightforward use of templates.

5

u/WalterBright Aug 20 '12 edited Aug 20 '12

You can use template metaprogramming for things like creating DSLs, but it's mostly used for what I suggested. Even the DSLs, however, can be thought of as creating generic reusable components.

For example, one can create a regex engine that generates custom code to deal with each particular regular expression.

2

u/Bzzt Aug 20 '12

so you're saying there's regular programming with templates, and then there meta-programming with templates. whats the difference between those?

2

u/greyfade Aug 20 '12

Using it for straightforward type substitution is a kind of metaprogramming.

The more abstract things you can do with templates (including compile-time computation and the truly magical things they did in Boost::Phoenix) are decidedly less often useful.

1

u/[deleted] Aug 22 '12

Templates are, by definition, a metaprogramming facility. Just like macros. Metaprogramming isn't just code that reasons about itself, it's also just code that "writes" other code in a structured manner (or unstructured in the case of macros). :-)

21

u/[deleted] Aug 20 '12

[removed] — view removed comment

16

u/WalterBright Aug 20 '12

I've often misunderstood it, so no worries there!

7

u/[deleted] Aug 20 '12

I really don't understand how template meta-programming can be an productive way of coding.

Many of the most basic C++ libraries are basically template meta-programming - like std::vector, std::string and that sort of thing.

It's a perfectly useful tool as long as you don't overuse it in your own code.

The last use I made of this is my digital audio program - where I need to be able to accept various different sample sizes and sample layouts. So I have a generic "Samples" class and then I have specific implementations that extract and convert the actual sample when I get down to it.

-5

u/jokoon Aug 20 '12

vector and string are reusable code, not code written by programmers who make an user-end application.

Well yes your audio example fits, but other that's not something you see often.

8

u/TheCoelacanth Aug 20 '12

If you're going to limit it to end-user applications then, obviously, template meta-programming isn't useful. The whole point of template meta-programming is creating reusable generic code that is as efficient as code hand-written for the specific situation. That's primarily useful for libraries.

-4

u/jokoon Aug 20 '12

Well it depends what you mean by reusable code, libraries are reusable code, they take care of the low-level stuff, and a lot of those libraries are already done in C or C++ using a procedural approach, because that's hat most libraries do, providing wheels for you to not reinvent them.

Unless there are many new kinds of algorithms invented everyday, or unless you intend to rewrite all kernels and drivers in C++, I really doubt meta-programming will be the generic reusable code generator graal.

Of course it will be a nice feature for certain situations where you need them, but I've yet to be convinced about how they can be provided useful. I mean the abstraction has to stop at one point, a language has to be a solution, not a problem.

8

u/TheCoelacanth Aug 20 '12

Every generic container library worth mentioning written in C++ uses template meta-programming to support efficiently using any type. Any container library written in C is either less generic, because it doesn't support any type, less efficient because it uses void* (as in the case of qsort being much slower than std::sort) or it does meta-programming using macros.

I have yet to see a library that is both as generic and as efficient as what is possible with TMP that doesn't do some form of meta-programming.

5

u/[deleted] Aug 22 '12

I can't think of where you can need it other than containers.

So you're one of those people who reimplement <algorithm> over and over? ;-)

2

u/nroberts666 Aug 27 '12

Abrahams's book explains some cases where you may desire basic TMP.

To consider why it's worthwhile you need to look at its past. There are two basic examples of TMP that are pretty important:

  • expression templates

  • tag dispatching.

The former is more difficult to talk about quickly but can be found with google. It's also less commonly used. Tag dispatching on the other hand is essential to understanding the STL. An example of tag dispatching can be seen from a stack overflow answer I wrote:

http://stackoverflow.com/questions/4688177/how-does-iterator-category-in-c-work/4688258#4688258

I would not agree that simple use of templates is the same as metaprogramming. Metaprogramming is compile time operations that review types and decide things. Tag dispatching is a rudimentary version of this. With TMP though you do not necessarily need the tags. You can write generic functions that work on any type, or are available for only certain concepts, without having some predetermined method of fetching the clues you need to do so...you can analyze the type and decide.

I've used TMP to implement and use a compile time dimensional analysis library. This saved me and my team many hours debugging equations in our physics models. I also used TMP to implement reflection in C++, which allowed us to write generic dialogs for new or changed record types.

It has its uses but it's very advanced and you have to carefully weigh the cost of teaching people how to do it vs. the time it can save you. It also greatly increases compile times.

1

u/yelnatz Aug 20 '12

I'm a novice programmer with C++. I basically code it like C with objects. lol

Can you elaborate what you meant with 'template metaprogramming'? Thanks.

5

u/sellibitze Aug 20 '12

template metaprogramming refers to writing programs with the help of templates that actually run at compile-time.

8

u/[deleted] Aug 20 '12

Saying they "run" at compile time is a little misleading - perhaps better to say that they are expanded at compile time to generate code that is later run?

(Yes, I know the template metaprogramming language is in fact Turing-complete, but it's conceptually better IMHO to think of that phase as "template expansion" and the phase where the machine language actually executes as "running".)

3

u/zokier Aug 20 '12

I think that's the distinction between "just using templates" and "template metaprogramming".

3

u/[deleted] Aug 22 '12

Agreed, and I often prefer the term "template instantiation" instead of "expansion", which is normally reserved for macros. Templates are similar to macros, but not quite, and it's best to not confuse them.

26

u/ivan-cukic KDE Dev | Author of Functional Programming in C++ Aug 20 '12 edited Aug 20 '12

Abstractions are important. While most of the people think those introduce performance penalties, it is not necessarily true. Template-based abstractions can be quite faster than their C counterparts.

Here's my variation of a famous example:

  • 1 - sort (myvector1.begin(), myvector1.end());

  • 2 - sort (myvector2.begin(), myvector2.end(), myfunction);

  • 3 - sort (myvector3.begin(), myvector3.end(), myobject);

  • 4 - qsort(array, size, sizeof(int), cmyfunction);

Speed of those, when compiled with gcc -O3. Array is of size 1MiB

  • 1 - Test: Original 46ms

  • 2 - Test: Function 56ms

  • 3 - Test: Class 36ms

  • 4 - Test: C QSort 63ms

So, the C version is the slowest, followed by std::sort with a function pointer passed to it.

The version with the most abstractions - generic algorithm (std::sort) and a functor (class) produced the fastest code.

New C++11 improves safety, readability and performance compared to the old C++. It might be confusing if you are mostly a C programmer using a C++ compiler.

18

u/greyfade Aug 20 '12

Oh, God no.

It's much easier to read the older code (at least for me). This also makes it easier to get new programmers integrated into our existing code base.

It may be easier to read the old code when you've been reading it for 14 years or so. The language has moved on and has improved significantly enough that I feel it's necessary to call it an entirely new language.

It works on the compilers we already have. No need to get Visual Studio 2012 or the latest gcc just to compile code that already compiles and works. It even works in Visual C++ 6.0. That's just awesome if you ask me.

Well, no, it doesn't. Several keywords have been deprecated or given a new meaning: auto, for example, does automatic type deduction now, and is no longer a storage class specifier. And code that once worked on Visual Studio 6 will throw numerous compile-time errors and warnings in newer compilers.

Why is that? Well, Visual C++ 6.0 never actually supported standard C++. It supported a dialect that was riddled with bizarre bugs. VS6 programmers learned to avoid any code that would trigger surprising behavior long ago, but all of those things are fixed in any compiler that actually tries to comply with the standard.

Even VS2012 fixed a lot of long-standing bugs, and I'm certain you could find code that VS6 compiled without error that VS2012 will now choke on.

I have looked forward to the day that Borland C++ Builder and Visual Studio 6 would finally end the span of their useful life so we as a community could move on to bigger and better things. The language is better now. Yes, it's different, but it's better. A lot better.

Enough so that it's worth learning modern idioms.

4

u/[deleted] Aug 20 '12

[removed] — view removed comment

2

u/slavik262 Aug 21 '12

I hope that part of the transition was to stop using auto_ptr and switch to unique_ptr, yes?

17

u/___1____ Aug 20 '12

I think you should get wit the times :S

Modern C++ has developed for a reason. Modern C++ IS easier to read once you have learnt how the abstracts work, I can understand why someone might prefer a handwritten loop to std::transform if they hadn't used higher order functions. There are other reasons too, such as it typically is more generic and easier to reuse.

Also what you may not see at first is that C is chronically unsafe.

   T ip*=new T(1);
   T jp*=new T(j);

new can throw, if it throws on jp then you lose ip, and if ip had destructors that had to run, well they won't be.

C++ is full of such things, which is why it is critical to use the std containers because they deal with such things perfectly. The natural progression from the std::containers is the std:: algorithms and so on.

I highly recommend reading, effective C++, exceptional C++, and modern C++ design. I would find it hard to believe that after reading that you wouldn't code differently.

2

u/Lord_Osis_B_Havior Aug 30 '12

RAII is well within C++-03 style.

1

u/___1____ Sep 04 '12

sorry, I fail to see your point.

The sort of code that the OP was talking about is the sort that doesn't use Boost, C++11 and smart pointers. I see it all the time and it is unsafe.

2

u/Lord_Osis_B_Havior Sep 04 '12

My point was that long before C++11, code like this:

T ip*=new T(1);
T jp*=new T(j);

was deprecated in favor of RAII.

2

u/___1____ Sep 04 '12

true, but I never implied that is wasn't, non the less people still wrote code like that and people (like the OP) still code like that today.

10

u/darkbeanie Aug 20 '12

Back around 1990-1992 when I was still in high school, I actually learned C++ before I learned C (all I knew up to that point was BASIC and Pascal). I loved the ideas of object oriented programming, and I loved the bare-bones utilitarian C style syntax in both languages. I ended up getting jobs a few years later where I did coding in both.

I had a bit of a hiatus from them professionally however, when my career took me through stints of network administration and software development with other tools. I did some C occasionally, but didn't keep up with C++ as much. By 2007-2008, I'd realized the language had changed so much, a lot of modern C++ code was almost unreadable.

And now most of the coding I do is for embedded (ARM Cortex, and some PIC), and that's all in C which for the most part is still the same language I learned as a teenager. I feel like C++ is marching on without me, and it's becoming so complex and so far removed from its original form I can't imagine what it must be like for new developers.

18

u/pjmlp Aug 20 '12

<rant> To be honest I think most new developers are too lazy to learn anything besides JavaScript. Even with other languages, which are simpler than C or C++ to learn, they seem to have problems. </rant>

As they say at CERN, you can write FORTRAN in any language...

15

u/_Qoppa_ Aug 20 '12 edited Aug 20 '12

Couldn't agree more. I learned C++ back when including iostream**.h** was correct, and I stopped using C++ right around the time of the TR1. Reading modern C++ code feels like I'm reading a different language. My instincts have me creating raw pointers and arrays, but everyone is telling me I should be using shared/unique/weak_ptr and the standard array class instead. If I ever need to use C++, I'll need to start from the beginning again.

Someone needs to create a "C++11 for people who used to program in C++ but no longer recognize the language" guide.

8

u/darkbeanie Aug 20 '12

This is exactly what I was just thinking!

The title I had in my head is "Learning it All Over Again: C++ For Former C++ Programmers"

2

u/spinwizard69 Aug 20 '12

C++11 is a new language! It is an evolution that tries to effectively fix issues from the past and deliver new programming features. So of course there is a learning curve. Frankly it is no different that a new version of JavaScript, Python or Java, you have to embrace the new features to really benefit.

8

u/sellibitze Aug 20 '12

Check out what B. Stroustrup has to say on this topic.

6

u/snarfy Aug 20 '12 edited Aug 20 '12

Visual C++ 6.0.

It's easier to read because you've been using the old style for 14 years. You are missing out on a lot of improvements in the language. GCC and even VS 2012 express (with c++ support)are free downloads.

I use to feel the same way but then I realized I was becoming a dinosaur, fast. At some point you stop looking at development with wonder and fascination and start looking at it as more boilerplate code to write before you can go home and not touch a computer. This is the mistake. Do whatever you need to do to keep interested in learning all the new tech.

19

u/pjmlp Aug 20 '12

No, I think that it is about time C++ gets to replace C, as we need safer systems programming languages.

Sure, C++ can be as dangerous as C, but it provides the tools to write safe code if one so wishes, specially with the new C++11 standard.

I seldom use C, unless I am forced to make use of it, given hardware constraints, or project requirements.

As for the language's complexity, complex problems require the ability to express complex abstractions, every language that joked about C++ complexity ended up being as complex as C++.

I use a few JVM and .NET languages at work, and while the grammar might be simpler to use, actually the sematic is more or less at the same level as C++, specially when coupled with metaprogramming frameworks.

As for the code itself, it if is working, why rewrite it?

11

u/[deleted] Aug 20 '12

So far, from my experience, the best C++ coders I've worked with all came from C. The problems I see with new C++ only programmers, is that they get so wrapped around code organization, and utilizing the features, that they don't understand what is actually going on. I've seen plenty of perfectly functioning C++ programs written by these people, that were astronomically bad in terms of memory use and performance. I'm talking about nested classes, cranking through a copy constructor, and performing 10,000 memory allocations per copy.... I didn't believe it either till I wrote some debug code and watched. For them, cranking through a single MP3 file went through 160,000 allocations. They had zero idea of what was under the hood, and even less about how to fix it without wrecking their whole class hierarchy. I agree that there is a time and place for C++, and I like many of the features myself, but I don't want to see it create a generation of lazy Java programmers either. I don't want to hear the "we have faster processors and more memory" so it doesn't matter. It always matters.

7

u/spinwizard69 Aug 20 '12

Every generation supplies its own set of stupid programmers. It is a mistake to believe that because a person has a fresh diploma he is somehow smarter than you. This is seldom the case.

7

u/pjmlp Aug 20 '12

I think this applies to any developer that learned to program in the last decade, regardless of the language.

0

u/snarfy Aug 20 '12

I thought Linus made a pretty good argument about c vs c++ in systems programming. Basically, it came down to this:

A = B;

Taken out of context, in C, you have a reasonable idea of what the assembly language output will be. In C++, you have no idea what that will produce. Are A and B objects? Is assignment overloaded? Will it throw an exception? The only way to know is to have full context, which makes the code difficult to analyze without fully compiling it.

10

u/mhayenga Aug 20 '12

Are A and B ints, floats, function pointers? Complaining that you don't know what operations will occur is one thing, but as far as code understanding goes, not knowing the underlying types is the real problem. Even the c code in the linux kernel has this when they copy members from structs, no context within the function. You have to grep the source to find the definition and data types. Not knowing full types given a functions context is not unique to c++.

5

u/snarfy Aug 20 '12

You are right. My comment is wrong. I believe Linus's argument was about maintaining the kernel (specifically, looking at the output of patch and merging), and not systems programming.

11

u/jbandela Aug 20 '12

Along the same vein, in C with the statement

f(); 

taken out of context, you have no idea what happens. If you forgo all function calls you can have a good idea exactly what assembly code is being generated.

0

u/[deleted] Aug 21 '12

You are missing the point. f() does exactly one thing, it calls f, you can look it up by it's name and be done with it.

A = B in C++ on the other side doesn't allow you to just look it up. None of the stuff that gets called is mentioned by name. It's hidden between layers of automatic type conversion, virtual functions, exceptions, proxy classes and operator overloading. You can try look it up for two hours and still have a wrong idea of what actually happens because you overlooked some obscure language detail.

C shows you what the code does, as everything is explicit. C++ does not, as a lot of stuff happens implicitly due to automatic magic happening in the background that is not expressed in code.

4

u/[deleted] Aug 22 '12

And yet, no sane C++ programmer manages to end up spending two hours finding the definition for the assignment operator of a well-defined type…

Linus is being a drama queen, as always, and that's why we love him, but this isn't a particularly good criticism of C++. C++ does make it possible to do more things implicitly, but there's no requirement that it has to if that's not your preferred style of coding. Meanwhile, the stricter type system alone would be a good reason to use C++ over C in systems programming.

3

u/[deleted] Aug 22 '12

And yet, no sane C++ programmer manages to end up spending two hours finding the definition for the assignment operator of a well-defined type…

Try to understand some of the more crazy boost libraries by only looking the source code, see how long that will take you.

this isn't a particularly good criticism of C++

It's a perfectly valid one. With C you see what the code does, with C++ you don't. That doesn't make one better then the other, as sometimes you don't want to see everything, i.e. destructors being automatic stops you from accidentally missing a deinit() call, but that doesn't make it any easier to judge what a piece of code is doing when it's all implicit and hidden from the view.

3

u/TheCoelacanth Aug 22 '12

Try to understand some of the more crazy boost libraries by only looking the source code, see how long that will take you.

Template metaprogramming is certainly hard to understand but most C++ code doesn't make extensive use of TMP like Boost does.

1

u/zvrba Aug 23 '12

With C you see what the code does

You don't: take for example implicit arithmetic conversions.

1

u/[deleted] Aug 23 '12

Yes, but those followed some fixed rules that you can look up and the compiler can give you a warning if you like. In C++ everybody can define his own rules and the compiler won't be of much help.

1

u/[deleted] Aug 22 '12

Try to understand some of the more crazy boost libraries by only looking the source code, see how long that will take you.

Here's an easy solution to that problem: Don't use boost libraries in your kernel code…

You don't seem to realize that all the features of C++ are opt-in.

-2

u/CBresp Aug 22 '12

Yes but you are at this point failing the turing test.

3

u/[deleted] Aug 22 '12

f() does exactly one thing, it calls f

Unless there is some macro somewhere...

0

u/[deleted] Aug 21 '12

Well, the same problem happens in C++. I don't think that example addresses the objection sufficiently. The point is, C++ introduces more context-sensitive constructs as basic language features.

I prefer C++ over C, by the way, mainly because I like objects and overloading operators (appropriately), and hate function pointers.

2

u/pjmlp Aug 20 '12

What about Ada which is used for systems programming and also supports operators redefinitions?

Given that Symbian is coded in C++, Mac OS X uses C++ in the IO Kit and Windows is slowly migrating to C++ with COM at the kernel level, C++ will eventually take C's place, regardless of what Linus thinks.

1

u/f2u Aug 20 '12

Ada lacks an assignment operator, so this specific example doesn't work. Assignment can only be customized in a rather restricted way (compared to C++). You can install a type-specific callback which is invoked after the assignment has already happened.

1

u/pjmlp Aug 20 '12

I know that, but it is also open to side-effects as snarfy was complaining about C++.

We need better languages for systems programming, not something that it is mostly from 1970.

5

u/[deleted] Aug 20 '12

I don't find that keeping things simple and doing it with C++ needs to stand in contradiction to one another. One can program complicated in any language. It is just a matter of setting up rules for your programmers to follow when designing things e.g. in our company we need to run MISRA and LINT on all our code plus have style guide in what is allowed and then have code reviews to enforce it.

9

u/[deleted] Aug 20 '12

I also like simple and readable code, which is exactly why I prefer modern idioms to "old style" C++. Specifically:

  • Modern C++ encourages usage of free functions (vs class methods) and I find them more local and easier to reason about.

  • The C++ Standard Library is well documented and finally well implemented by most compiler vendors - I don't have to learn everybody's pet collection and string classes any more.

  • In "Old style" C++ pretty much every object gets created on the heap for some reason and it is next to impossible to track where all these objects get deleted. Plus, the code is notoriously non-exception safe, which is why most old projects disable exceptions, and then they can't use constructors properly and it all gets downhill from there.

4

u/jbandela Aug 20 '12

C++ can be programmed as a high level language such as Python. The difference is that if you want to write extensions in Python you use C(or C++). With C++, you write an "extension" in C++. It would be a mistake to say that Python is very complicated and then cite all the bad stuff you could do in C. With C++, I also think it is a mistake to say it is hard to use and then cite stuff that are there mainly for library writers. Such things as template metaprogramming, r-value references, etc are meant to be used by library authors. In fact, I think that delete should only be used by libraries. At Dr. Dobbs, Andrew Koenig http://www.drdobbs.com/cpp/c-primer-5th-edition-part-3-smart-pointe/240004805 has an article stating that it is hard to come up with an example where user written copy-constructors are required.

I think the biggest deficit in C++ is the relative lack of standardized libraries compared to say Java or C# http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/C-11-VC-11-and-Beyond. The new features enable simpler libraries, and thus an easier to use language.

1

u/bruceme Sep 01 '12

Not particularly... I've been a coder for 18 years, I work on old legacy product that's half C++ and half C#. Whenever I get into the C++ code I have to tread more carefully and I can't do any of the well engineered short cuts C# can do. I'm sure my C++ code runs faster, but when you have 2.5mil lines of code and customers that just want more features, I could care less about speed.

1

u/aninteger Sep 02 '12

Well, you're comparing C++ versus C# though.. I'm comparing the older C++ to C++11. I think most people would say they prefer C# over C++ assuming they're not working on an embedded device or something with low memory requirements.

4

u/djfnerd Aug 20 '12

I'm bits and bytes embedded programmer whose recently been thrown into writing desktops apps. Oh do I miss my C only environment. C is so simple and elegant to me, and C++ (or anything modern) just hurts my head. Also, no, I am not near retirement age :-)

4

u/cran Aug 20 '12

As an old C programmer, I prefer Java, but I can appreciate the changes added to C++11. What I have never been able to wrap my head around is why C++ became this. One of C++'s strengths is that it is, essentially, C ... very close to the metal, very efficient, very fast. It seems to me that C++11 is not really C++ at all, but a C++ - ish language that compiles into machine code. I see it having more in common with JavaScript/V8 (a la node.js) than with the C language. It is, essentially, very high-level programming language that gets turned into machine code prior to execution ... but your programming is never anywhere near the machine itself.

It's not a bad thing ... but it's just not what I would have expected to become of C++. It's as if an entire programming paradigm disappeared right in front of our faces.

4

u/afiefh Aug 26 '12

It is true that C++11 encourages more high level programming, but I always felt that the more natural style of writing C++ is not not treat it as "essentially C." You could write very highly abstracted code in C++03 as well, C++11 only makes it easier.

2

u/[deleted] Aug 20 '12

code style is a matter of personal choice, you probably don't like it because you're not used to it or maybe you're afraid of change and that's fine BUT using old compilers is really a bad practice.

yes companies usually don't update compilers for years but that's a mistake, it's not just about supporting new features, it's about bug fixes and creation of better code. even if there was no such thing as c++11 and new features is still highly recommended to update compilers as often as possible.

3

u/Fabien4 Aug 20 '12

C++11 tends to simplify the code a lot, and render it far more readable.

Compare

for (std::vector<MyLongType>::const_iterator i= v.begin(); i != v.end(); ++i)

and

for (auto i: v)

12

u/STL MSVC STL Dev Aug 20 '12

Note that "for (auto& elem : range)" should be used by default. It observes and/or modifies elements in-place.

"for (auto e : r)" copies each element. This doesn't permit in-place modification (e can be modified, but it will not affect the original range). Even if you're just observing, it's significantly less efficient if the element has a nontrivial copy constructor (e.g. string, etc.).

3

u/Fabien4 Aug 20 '12

You should use auto const& elem: range then. By default, you don't want to modify stuff. Using a non-const reference means that you intend to modify what the reference points to.

it's significantly less efficient if the element has a nontrivial copy constructor (e.g. string, etc.).

What do you mean by "significantly less efficient"?

5

u/STL MSVC STL Dev Aug 21 '12

You should use auto const& elem: range then.

That's also fine.

What do you mean by "significantly less efficient"?

Consider vector<string> v. for (auto s : v) and for (string s : v) are equivalent. Each iteration, an element of v will be copied into s. string has a nontrivially expensive copy constructor.

0

u/Fabien4 Aug 21 '12

I understand the basic theory. However:

- Are you sure the copy isn't removed by the compiler?

- If it isn't, what's the actual performance hit?

9

u/STL MSVC STL Dev Aug 21 '12

Yes, I'm sure. (As I'm an STL maintainer, I have a pretty good idea of what the compiler will and won't do.) The compiler will see, in general, a dynamic memory allocation, a memcpy, reads to the copied bytes, and a deallocation. Compilers are simply not smart enough to notice when all of this work can be omitted.

The actual performance hit, in the worst case, is N dynamic memory allocations and deallocations, plus N * M copied bytes, where M is the average length of the strings in the vector. (If some strings activate the Small String Optimization, you still pay the byte copies but avoid those allocations.)

It's a big deal, which is why I emphasized it so strongly.

1

u/mttd Aug 20 '12 edited Aug 20 '12

Out of curiosity -- when using "auto", is it possible for a SufficientlySmartCompiler to elide copy here if no modifications are made later on (would "const auto" be in any way useful?) or generate code as-if reference was used:

range_declaration = *__begin;

// I'm guessing that's the one we're worried about; exposition-only syntax per http://en.cppreference.com/w/cpp/language/range-for.

If not, are there any other optimizations inhibited when using "auto &" instead of "const auto &" when observing only?

1

u/bob1000bob Aug 20 '12

maybe, (if you don't modify the temporary) but why program in such way. "const auto&" and just "auto" (don't take primitives by ref when you don't need to) when observing and auto& when modifying.

2

u/Bzzt Aug 20 '12

Some of my favorite C++ code was the BeOS gui code. Those guys really worked to keep it simple and easy to read. Quite a constrast with the ugly wxwindows or microsoft stuff. No macros, straightforward classes and inheritance. Super clean!

2

u/bob1000bob Aug 20 '12

I don't understand this point.

Wx, com and MFC are examples of bad modern C++.

1

u/Bzzt Aug 20 '12

Point is that the BeOS toolkit was an example of good code from that late 90s era, IMO.

2

u/bob1000bob Aug 20 '12

thanks. I didn't realise you weren't making the comparison with modern code.

I checkout the Beos code then.

1

u/jaberwocky69 Aug 20 '12

I guess if it isn't broke then don't fix it. Amirite? But brand new code straight from the forge should be the new C++11 code. (I guess, I'm not much of a programmer so my word isn't definitive.) Besides, jump on the bandwagon or get left behind with the cow manure.

1

u/Heuristics Aug 26 '12

Take a look at vtk/paraview:

http://www.vtk.org/ http://www.paraview.org/

These two projects are c with classes (due to their age) and they are horrible. This is because they use inheritance for everything which results in a typical call stack being about 40-50 levels deep. Whenever you deal with some class you never know exactly what class code you are dealing with.

C with classes looks fine when you start a project and all you know of is perhaps 1-2 levels of abstraction but as your project grows over the decades things get sucky.

1

u/PrestonBannister Nov 07 '22

This is an ancient topic, but ten years on, things have not really changed.

When writing code to get low-level, bare metal performance, then C++ remains my preferred choice. This choice has not changed in ~30 years. C++ classes are good .. when carefully used.

At the same time, Stroustrup and friends thoroughly borked "C with Classes". This means there are large swaths of the C++ language standard that I consider a hideous mistake.

Seems in the very latest (2017 and later) versions of the C++ standard there is an attempt to correct the hideous errors of the past. Too late.

C++ remains a hideously dangerous tool for average programmers. Old or new.

The C++ standards crew presumes they are smarter than the average programmer - but the C++ language is a poor choice for the average programmer. The standards crew assumes (without proof) that std:: is smarter, but is not if you subtract average programmers.

I use C++ but mostly ignore std:: (too much stupid).