Slashdot Mirror


Bjarne Stroustrup Announces the C++ Core Guidelines

alphabetsoup writes: At CppCon this year, Bjarne Stroustrup announced the C++ Core Guidelines. The guidelines are designed to help programmers write safe-by-default C++ with no run-time overhead. Compilers will statically check the code to ensure no violations. A library is available now, with a static checking tool to follow in October.

Here is the video of the talk, and here are the slides.The guidelines themselves are here.

48 of 262 comments (clear)

  1. Wait what? by Virtucon · · Score: 4, Funny

    If you take all the fun out of finding memory leaks and stack overflows what fun is there to C/C++? I mean I just love using AutoPtr everywhere, it's perfect!

    --
    Harrison's Postulate - "For every action there is an equal and opposite criticism"
    1. Re:Wait what? by tepples · · Score: 2

      If you take the drudgery out of finding stack overflows, then perhaps you'll have more time to d%%% around on //||] stackoverflow.com.

    2. Re:Wait what? by Pseudonymous+Powers · · Score: 5, Funny

      Everything in C++ is now deprecated except the word "safe". So you should really be using safesafe::safe_safe_safe in such situations. And in all other situations. When in doubt, just keep typing "safe" until it's safe.

    3. Re:Wait what? by Darinbob · · Score: 2

      And reference counting has been known to be a terrible garbage collection technique for four decades. Yes, it's problematic to add good garbage collection to a language compiled to bare machine code, especially with smaller CPUs or less memory, and so it the reference counting technique keeps getting used even in modern times.

      It is actually easy to manage the memory yourself (though less efficient than incremental generational scavaging techniques) but there has been a generation of programmers trained to believe that manual memory management is evil. There also seems to be this sort of mystic vision that if only we could solve the memory management problem that programming will finally become pain free and we will no longer need to learn to be disciplined. The whole goal, probably driven by management, is to allow poorly trained engineers to write software.

    4. Re:Wait what? by Darinbob · · Score: 4, Insightful

      If you're using a professional code base, then you're better off NOT using all the latest features just because they're new! Sure, learn about the new language features, but that doesn't mean you should embrace them. Let other people be the guinea pigs.

    5. Re:Wait what? by Pseudonym · · Score: 2

      They are just chicken-shit scared of Swift, Rust and Sappeur.

      The language that everyone hates is not scared of the languages that nobody uses.

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
  2. As always with C++, the truth is more nuanced by beelsebob · · Score: 4, Interesting

    For example, one of the guidelines here is to always prefer make_shared over std::shared_ptr(new ...). That's good advice for a couple of reasons
    1) it allocates your memory for the shared_ptr control block and the object contiguously
    2) it means you can't separate the allocation from the creation of the shared ptr and end up with an owner who's not looking at the shared ptr in-between.

    However, it also means that if you have any weak_ptrs pointing at the end of that shared_ptr, the object itself won't go away until all the weak_ptrs do too (because the control structure won't go away until they do, and they're contiguously allocated).

    1. Re: As always with C++, the truth is more nuanced by slack_justyb · · Score: 2

      Agreed, however some of us inherit the problems and do our best to convince the uppers to allocate time to clean things up. Let's not forget that there are a whole slew of Lennart Poettering wannabes out there that have everything to prove using some of the most horrible coding styles that could ever exist.

    2. Re:As always with C++, the truth is more nuanced by spitzak · · Score: 2

      We're still going to need two objects, one a base object and one a pointer object. If we use raw pointers, the reference count will not be incremented and decremented properly, and we need the reference count to reliably be equal to the number of pointers extant. Therefore, the pointer needs to have its own copy constructor, copy assignment operator, and destructor, which will call the appropriate increment and decrement methods (the decrement method to include the deletion as a special case). If we keep the reference count with the object instead of with the pointer, we can keep the pointer size down without indirection.

      This is no more complicated than what has to be done with shared_ptr. And you are confused, you can use raw pointers all you want, as long as you know there is a shared_ptr pointing at the object. This happens in many cases.

      We need to document heavily that IRefCount (or something more according to C++ naming) is to be inherited virtually, as otherwise we could have more than one reference count if we add it to multiple levels of a class hierarchy. (C++ multiple inheritance can be tricky to get right.)

      So, we've got the pointer object, which will contain the pointer and have some attached functionality, and the reference count mixin. This works as long as we can easily modify the class structure, but it does require a fairly sophistication serialization/deserialization system to keep the modified and unmodified objects in sync. In addition, since it changes the memory layout of a class, it can lead to slow compiles.

      It's not a "mixin". It is a base class. This avoids your supposed problems.

      With this, we also don't get weak_ptr functionality. A shared_ptr object has a shared pointer count and a weak pointer count. This makes it possible, for example, to have a circular list that can be destructed: have one link be a weak_ptr and everything else a shared_ptr. The object itself is destructed when the shared pointer count goes to zero, and the shared_ptr object when both go to zero. (A weak_ptr does nothing on its own, but can be converted to a shared_ptr if the target object is still there.)

      You can implement weak_ptr in EXACTLY the same way make_shared does it. The object is destroyed but the memory is not freed until the weak_ptr count goes to zero. In fact it is fairly easy to have "an object that supports weak_ptr" be a different base class than the plain refcounted object, thus you don't pay for the weak_ptr overhead on every pointer (though you can't make a weak_ptr unless the object is derived from the correct base class).

      I don't see this as being easier than shared_ptr, although it is superior for some purposes.

      It is enormously easier when you have to do the equivalent of make_shared_from_this (or whatever they called it), and to avoid constructor shenanigans so that the user has to call make_shared and not construct raw objects. The implementation is about the same as shared_ptr.

      Boost called this an "intrusive pointer" but they did not support weak pointers. That could be done with a few extra calls. It was a bit ugly as they tried to not define the base class (instead it called functions that the class defined to inc/dec the ref count), I think insisting that everything be based on a refcounted base class would work just fine.

    3. Re:As always with C++, the truth is more nuanced by Pseudonym · · Score: 2

      Yet still no modules.

      One of these days, Stroustrup will realise (like Stepanov did) that Simula's object model was a mistake.

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
  3. News at eleven by Anonymous Coward · · Score: 3, Informative

    Imperative programmers reinvent functional programming concepts, but in a shitty way. More at eleven.

  4. Re:Frist! by Anonymous Coward · · Score: 3, Funny

    "print" is deprecated. You must now use the safe_print_n function and get a safe pointer back using the SafetyFirst() method of the SafeLiteral class.

    Because safe by default, amirite?

  5. Bjarne should not be writing that by Carewolf · · Score: 3, Insightful

    He has a connecting to all the features he put into C++ and any coding guidelines should include thing that should not be used. First among those are exceptions, unfortunately Bjarne has never wanted to admit C++ exceptions were a mistake.

    1. Re:Bjarne should not be writing that by Carewolf · · Score: 2

      It is not just Google that bans them, it is industry best practise not to use them. While you can make exception-safe code by containing all state information in classes that can properly unwrap them, it is extremly tedious and very error-prone to do. Basically the only safe thing to do after catching an exception is quiting, which means you might as well exit, crash or catch a signal.

    2. Re:Bjarne should not be writing that by goose-incarnated · · Score: 2

      I don't realy get why people write this nonsense.

      You are at an ATM, you insert your card, the card can not be read: DamagedCardException.

      The card can be read and you are asked to enter the code, code is wrong: InvalidCodeException

      You enter the code three times wrong: CardSwallowedException

      You enter the code correctly and want to withdraw $1000, but the bank does not acknowledge: TransactionNotPossibleException.

      NONE of the above exceptions will terminate the ATM software but will return with a hopefully meaningful message to the main menu.

      I wouldn't consider any of those to be exceptions; return DamagedCard, InvalidCode, CardSwallowed or TransactionNotPossible (+ TransactionSuccessful). This allows the caller to be a state machine that changes to different states simply by switching on the return value of the function:

      while (1) {
      state = readCard ();
      switch (state) {
      case DamagedCard: //...
      case InvalidCode: //...
      case CardSwallowed: //...
      case TransactionNotPossible: //...
      case TransactionSuccessful: //...
      }

      is a great deal cleaner than

      try {
      readCard();
      // Handle successful return
      } catch (DamagedCardException e ) {
      // Handle exception
      } catch (InvalidCodeException e ) {
      // Handle exception
      } catch (CardSwallowedException e ) {
      // Handle exception
      } catch (TransactionNotPossibleException e ) {
      // Handle exception
      }

      By classifying non-exceptional conditions as an exceptional out of the ordinary condition you tend to handle it in an ad-hoc way, treating it as an error. All of those conditions above are *not* errors, they are part of the logic for the ATM. Running out of money in an ATM is also not an error. These things should be handled in the state-machine for the main logic so that at least formal methods can be used to verify that the logic has a well-defined flow for every state. Moving logic out of the normal program flow is asking for errors when someone changes something and it is then not apparent by checking the program logic.

      I wrote ATM software for a long long time. Nothing was considered an exception - everything (including errors) was simply a signal to move to some other state which would handle the signal properly. Exceptions are most-used and well-loved by non-CS programmers, because it lets you place undocumented local jumps that bypass the documented logic-flow. Exceptions are hated by CS programmers for the same reason.

      --
      I'm a minority race. Save your vitriol for white people.
    3. Re:Bjarne should not be writing that by Carewolf · · Score: 2

      If your code isn't exception-safe, it's probably bad in several other ways. It's not that difficult to get it right, if you have a clue, and will avoid other problems. If you think industry best practice is C++ that isn't exception-safe, I don't want to work where you do.

      If you think it is easy, you are doing it wrong. It is as difficulty as coding thread-safe code without using mutexes and semaphores. Execution might be cut at any point in time and the state has to be consistent at that time. If you set a pointer to an array and then the length to it, you are not doing it thread-safe because an exception might come inbetween, which means something as simple as setting data needs to be controlled by state-classes that can rollback half completed state changes in case of an exception.

      The easiest way to get around it, is just to use functional programming style where you have little or no state, but that also implies reducing the multiparadigme langauge of C++ to just one paradigme

  6. Cost of safety by fragMasterFlash · · Score: 2

    Its nice to see efforts to drive the complexity out of the design/implementation of safe code but this won't due much to improve the already error prone task of debugging optimized code. You don't always have the luxury of running a debug build, especially when analyzing a crash dump from a customer and templated/STL C++ constructs are often too complex for debuggers to parse properly. Hopefully these efforts reduce the number of crashes enough to justify the added complexity of debugging the crashes that still occur.

  7. Ada had this in 1995 by david.emery · · Score: 3, Informative

    Ada95 added OO features including clear mechanisms (enforced by the compiler) on how to get OO design benefits without runtime performance costs or risks for dispatching.

    Much of what I've seen in C++ is a response to problems in the original language design, particularly gaps or errors of omission.

    Computer Science in the 21st Century seems to be full of stuff we knew about in the '80s and '90s, but forgot.

    1. Re:Ada had this in 1995 by david_thornley · · Score: 2

      What part of C++ OO imposes runtime performance costs? Virtual functions are one indirect access of a table that's likely to be in cache already. What are the risks in dispatching?

      Modern C++ is a successful attempt to make C++ into a much better language. You could call that a response to earlier problems, but it's not just a bunch of patches.

      Computer programming in the 21st Century seems to have problems with stuff we knew about in the 70s. Java's "finally"? Who thought that was a good idea?

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
    2. Re:Ada had this in 1995 by UnknownSoldier · · Score: 2

      > What part of C++ OO imposes runtime performance costs?

      Uh, the fact that it is designed for the uncommon single case instead of the common multi case. You want to optimize for the throughput, not latency.

      OOP (Object Orientated Programming) has terrible performance scalability since it has terrible D$ (Data Cache) usage. For high performance OOP is completely ditched in favor of DOD (Data Orientated Design). DOD is used heavily in modern game development, and HFT (High Frequency Trading.)

      I would recommend starting here:

      * Pitfalls of Object Oriented Programming

      Even Bjarne Stroustrup was ignorant of D$ usage and how it effects performance:

      * Why you should avoid Linked Lists, where someone subtitled it: Stroustrup learns how L1 Cache usage is critical for performance sensitive code.

      I would also read Mike Acton's presentation:

      * Typical C++ Bullshit

    3. Re:Ada had this in 1995 by Grant_Watson · · Score: 2

      C++ grew somewhat organically out of C. C is (IMHO) an excellent language, but its goals often differ from C++'s goals.

      I won't argue with your conclusion; it's true. But a lot of what was achieved in the research and design of the '80s and '90s was achieved by burning down the software stack and starting over. (Take Smalltalk for example.) People are rediscovering those things in a context where the existing stack matters and tackling the hard work of reconciling those developments with what we already have in a coherent way.

    4. Re:Ada had this in 1995 by david.emery · · Score: 4, Informative

      That "piece of shit" is in most modern commercial aircraft these days, as well as the ground ATC systems. Guess maybe you shouldn't fly, then, if that's your opinion, Mr Coward.

      There are legitimate criticisms that can be levied against any programming language, as well as against the Ada program. But this comment addresses none of them.

    5. Re:Ada had this in 1995 by phantomfive · · Score: 4, Interesting
      It reminds me of this quote:

      "It's quite apparent that the evolution of the C family of languages (C, C++, Java, C#) is converging on a language very like Ada, except unfortunately as a kludgepile rather than a clean design."

      --
      "First they came for the slanderers and i said nothing."
    6. Re:Ada had this in 1995 by david.emery · · Score: 2

      And that's what makes Ada95 (and subsequent versions) so interesting from a language design perspective. Ada95 built on the Ada83 language (which itself built on Pascal, as well as CLU and other research languages), adding OOP (including supporting concurrent objects in a way that I haven't seen in other "modern" programming languages in this era of multi-core processors). There are design trade-offs, and these are well-documented. If you're interested in such things, the published design team rationale documents (for both Ada83 and Ada95) should be required reading. Ada83: http://www.adahome.com/Resourc... Ada95: http://www.adahome.com/Resourc...

      What Ada95 accomplished was to graft a full OO design mechanism (i.e. inheritance) , while preserving type-safety (for scalar types, as well as "objects" or classes), keeping the safety properties (e.g. impossible without unchecked conversion to dereference a null pointer), and providing nearly 100% backwards-compatibility with Ada83. (There were a few inconsistencies, but these were at the edges of the language.)

      Oh, and Ada2005 adds support for pre-conditions and post-conditions that matches what Eiffel now provides for defining and enforcing contracts. And it does so while providing the SPARK subset that supports theorem-proving for proof-of-correctness (including concurrent programs), starting with "cannot generate runtime error". See https://en.wikipedia.org/wiki/... A lot of this grew out of David Luckham's work at Stanford on annotation languages such as ANNA and TSL, see http://www.springer.com/us/boo...

    7. Re:Ada had this in 1995 by UnknownSoldier · · Score: 2

      > Game programmers often use C++ (for various reasons).

      Performance is the #1 of reason, but yeah, C++ gets the right balance of power, compactness, performance, and multi-paradigm design which builds upon C's foundation.

      > What do you typically use to write programs?

      Just because I'm vocal, and passionate, doesn't mean I toss the baby out with the bath water.

      I would be stupid to ignore the wisdom of Bjarne Stroustrup:

      There are only two kinds of languages:

      * the ones people complain about and
      * the ones nobody uses.

      To answer your question:

      Pragmatic C++. (With some Javascript, since WebGL is my (current) day job)

      Which is the balance of the middle ground between basic C and the modern over-engineered clusterfuck of C++. Why do you think there was an "Embedded C++" movement years ago which removed all the Templates, Exception Handling, and RTTI junk? Gee, look, Ubisoft C++ usage does the exact same thing.

      To clarify, I use _only_ templates when it makes sense. Most of the time it doesn't. I use #define macro's where it makes sense. Most of the time it doesn't. I don't use Boost because it is over engineered 99% of the time. I uses classes where it makes sense. I use 3rd party libraries only when necessary. I use design patterns only when the model fits - instead of trying to shoehorn the code+data into a broken model.

      I've shipped enough games where a full build was 45+ minutes. This is insanity.

      Minimal C++ is the mantra. Use the expressive complexity and power of the language when it matters. Most of the time it doesn't.

      I just want the insanity of C++ to stop and address the common core issues instead of adding yet-another-flavor-of-the-month concept. Retarded ideas like 2D Graphics Rendering API proposal is the epitome of everything wrong with the committee. Completely out-of-touch with reality and solutions in search of a problem.

      When you _even_ have a C++ committee member admitting he writes in a sub-set of C++ himself you know the language has gotten too big. /Oblg. Murphy Computer Law: Inside every large programming language is a smaller one struggling to get out.

      *ALL* programming languages suck. Most suck even more.

      Want to know someone else who hates C++? Andrei Alexandrescu. *Every* C++ programmer should read until they grok Modern C++ Design: Generic Programming and Design Patterns Applied Guess where he works on now? D (All Things D (programming language) - A Conversation with Andrei Alexandrescu.)

      When you even have Scott Meyers at a D Conference (DConf 2014: The Last Thing D Needs (Scott Meyers), you know the language has potential. D has its own problems but I would keep my eye on it. :-)

      As bad as C++ is, for my needs it is better then the alternatives.

  8. What instead of an exception? by tepples · · Score: 2

    Bjarne has never wanted to admit C++ exceptions were a mistake.

    What should a method that fails do instead of returning an exception? Should it instead be set up to explicitly return two different types of return value, namely the object that it's supposed to return if it exceeds or an object describing the failure if it fails?

    1. Re:What instead of an exception? by Yosho · · Score: 2

      I can't speak for the original poster, but as for myself, I think that conceptually exceptions are great, but the C++ implementation of them is full of holes and prone to abuse. As much as the Slashdot base loves to hate Java, I think Java got exceptions right.

      Notable differences:
      1) There's a distinction between checked (compile-time) and unchecked (runtime) exceptions. All C++ exceptions are unchecked.
      2) A method that can throw checked exceptions must declare every checked exception it can throw, and a method that calls another method that can throw checked exceptions must explicitly catch or re-throw them. These can be verified at compile time.
      3) Every object that can be thrown/caught must implement the Throwable interface, so it has a predictable interface and can be properly manipulated in an object-oriented manner.
      4) try/catch blocks also have a "finally" clause that is guaranteed to be run after the try/catch blocks complete, regardless of whether either one of them runs to completion or throws an exception out of the method. This is crucial for safely cleaning up filesystem/network resources -- the C++ alternative is only allocating objects on the stack and implementing destructors that clean up their resources, but then you have the restriction of not being able to allocate on the heap, and it may not also be obvious from looking at the try/catch block what the destructors are doing or in what order they'll be called in...

      I go back and forth between C++ and Java development a lot, and every time I go back to C++, I'm immediately reminded why C++ developers are so averse to using exceptions for error handling.

      --
      Karma: Terrifying (mostly affected by atrocities you've committed)
    2. Re:What instead of an exception? by tepples · · Score: 3, Informative

      Every object that can be thrown/caught must implement the Throwable interface

      Then have all exceptions extend a subclass of std::exception . The guidelines mention use of a subclass as opposed to using the built-in exceptions directly.

      the C++ alternative is only allocating objects on the stack and implementing destructors that clean up their resources

      Also called Resource Acquisition Is Initialization (RAII), or "automatic resource destruction" if you don't want to remind readers of the record industry (RIAA).

      but then you have the restriction of not being able to allocate on the heap

      You can take advantage of automatic resource destruction if you wrap your object on the heap in a smart pointer type (std::unique_ptr or std::shared_ptr as appropriate) on the stack. If that isn't appropriate in a given situation, C++11 supports a scope guard idiom using std::shared_ptr and lambda expressions. The finally factory described in the Guidelines is ultimately an update of a method described in a 2000 article by Andrei Alexandrescu in Dr. Dobb's .

  9. Sad, really by jandersen · · Score: 5, Insightful

    I think it is sad, looking around on the responses so far, to see, yet again, that the overwhelming response to this is to jeer at anything that is beyond people's comprehension. I guess what it boils down to is, that far too many who call themselves coders can't be bothered to sit down and work out a detailed plan before barging ahead. You get nothing but trouble from OOP if you think in terms of simple scripts, and that is particularly true of C++.

    1. Re:Sad, really by myrdos2 · · Score: 4, Insightful

      In short, I suggest that the programmer should continue to understand what he is doing, that his growing product remains firmly within his intellectual grip. It is my sad experience that this suggestion is repulsive to the average experienced programmer, who clearly derives a major part of his professional excitement from not quite understanding what he is doing. In this streamlined age, one of our most undernourished psychological needs is the craving for Black Magic and apparently the automatic computer can satisfy this need for the professional software engineer, who is secretly enthralled by the gigantic risks he takes in his daring irresponsibility. For his frustrations I have no remedy......

      -- Edsger W. Dijkstra

      I love this quote, and I say that as a C++ programmer. It falls in with my own philosophy, which is that the more complicated something is, the less likely people will get it right. And C++ is extremely complicated. It's not the OO design that necessarily trips people up, it's the sheer amount of minutiae you need to remember and the care you must take not to do something stupid.

    2. Re:Sad, really by phantomfive · · Score: 2

      that far too many who call themselves coders can't be bothered to sit down and work out a detailed plan before barging ahead.

      That's a good description of the C++ design process, and why the "approved" way of using the language is completely different than the "approved" way of not long ago.

      How many ways are there to allocate memory in C++? I'm starting to lose count.

      --
      "First they came for the slanderers and i said nothing."
  10. Re:As always, guidelines are for beginners by 140Mandak262Jamuna · · Score: 4, Insightful

    Just like "don't use goto", or "don't use threads", etc., these guidelines and recommendations are really great to prevent beginners from making hard to spot errors, but all those variations and features exist for a reason and have a use.

    Nobody uses GOTO anymore. With event driven programming and call back functions, it all spaghetti code strewn with COME FROM statements, effectively.

    --
    sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
  11. Re:Should file not found always be a fatal error? by Seq · · Score: 3, Insightful

    You just need to catch the crash. Though it would be helpful if we could pass along some additional information about the crash..

    Oh. Hmmm..

    --
    -- Seq
  12. Re:It's pointers all the way down, jake ! by The+Evil+Atheist · · Score: 2

    Unless you're dealing with hardware directly, you don't need pointers at all.

    --
    Those who do not learn from commit history are doomed to regress it.
  13. Re:It's pointers all the way down, jake ! by david_thornley · · Score: 2

    The other thing about GC is that it solves the resource deallocation problem for memory only. It doesn't support deallocating other resources which may be more important to deallocate promptly. (People are working on C and C++ garbage collection, and there have been attempts, but none have gained much popularity. Whether this is because nobody has worked hard enough, or because it doesn't offer a solution that much better than smart pointers, or that C and C++ just won't work well with GC is an interesting question.)

    --
    "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
  14. Re:Instrumenting c++ to behave like Rust by Tailhook · · Score: 4, Informative

    I found Rust

    I've found it best not to talk about Rust around here. The language has already accumulated a legion of haters at Slashdot. Rational discussion about Rust sans the office punklets happens at Hacker News.

    It was anticipated that Rust would motivate some progress in C++ memory safety. Some have argued that if that is all that Rust accomplishes it is worthwhile. Too bad an entire language has to be invented to get some folks off the dime.

    The uptake of Rust is so large though I don't think it's going to go away just because C++ adopts some degree of compile time memory safety. The language is great on it's own merits, there is none of that half century of baggage to slog through and the entire stack and all native Rust third part modules provide the same memory safety guarantees, barring 'unsafe.'

    These things, combined with the never ending stream of opportunities the segfaults and overflows that C/C++ cannot avoid providing will ensure a chunk of mind-share, haters be damned.

    --
    Maw! Fire up the karma burner!
  15. Re:As always, guidelines are for beginners by Bengie · · Score: 2

    I've ran into situations where not using GOTO resulted in much messier code that was harder to read. This rarely happens, but it does happen, and I always take a step back and try to find a better way than using GOTO.

  16. Re:Instrumenting c++ to behave like Rust by Grant_Watson · · Score: 2

    Half century? Are you counting from Algol?

    That said, the cruftiness of C++ is one of the things that keeps me from bothering to properly learn it, however much I respect its newer developments. Another is that its place on the scale of abstraction isn't often a place that I need to go personally: C or Python usually makes more sense for me.

    Where on that scale would you say Rust lies? Is its target use software that lies on the boundry between systems software and applications, e.g., web servers?

  17. Re:Instrumenting c++ to behave like Rust by Pinky's+Brain · · Score: 3, Insightful

    Seasoned professionals have given us decades worth of mostly unnecessary buffer overflows.

  18. Re:Should file not found always be a fatal error? by mrchaotica · · Score: 2

    You're trying to make me declare some sort of hard-and-fast rule to something that's really an issue of style, which I won't do. But here's a heuristic: if you expect to succeed in opening the file, you could probably go ahead and use the 'pythonic' 'ask forgiveness, not permission' pattern. But if you're trying to (for some reason) open only one of 50 files and expect the other 49 not to exist, then your loop should probably look more like

    for name in filenames:
    ....if isfile(name):
    ........f = open(name)

    instead of

    for name in filenames:
    ....try:
    ........f = open(name)
    ....except IOError:
    ........#do nothing

    Also, exceptions should be used much more sparingly in C++ than in Python because they don't work as well in the former.

    --

    "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

  19. Re:As always, guidelines are for beginners by Darinbob · · Score: 3, Informative

    I use goto. Sometimes. When you're in C then it's can be effective way to do a function clean up before exiting. Sure this can be over done but trying to avoid a goto like a religious taboo can also result in some pretty nasty code to replace it.

  20. Re:Should file not found always be a fatal error? by david_thornley · · Score: 2

    Having been handling errors for a long time before I ran into exceptions, I don't agree that having to constantly check some sort of error flag is better than using exceptions.

    --
    "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
  21. Re:Should file not found always be a fatal error? by narcc · · Score: 2

    Exceptions are one approach. The mistake is in thinking that one approach supersedes all others.

    It has more than its share of problems, which need to be acknowledged if we're to move beyond them.

  22. Re:As always, guidelines are for beginners by w_dragon · · Score: 2

    For C that's a perfectly reasonable use of goto. For C++ you should use unique_ptr or wrap your resource in your own object that you can stack allocate. RAII is a very nice pattern in C++.

  23. Re:As always, guidelines are for beginners by angel'o'sphere · · Score: 2

    RAII is not a "pattern" it is an "idiom".

    A pattern is independent from programming languages, idioms are thins you only can do in one/some language.

    e.g. using pointers and ++ to copy a \0 terminated string like this:

          strcpy(char* dest, char* src) {
                while (*dest++ = *src++)
                        ;
          }

    is an idiom ... supported by certain languages, not a pattern.

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  24. You just created a TOCTTOU race bug by tepples · · Score: 2

    for name in filenames:
        if isfile(name):
            f = open(name)

    Congratulations: You just created a time of check to time of use (TOCTTOU) race bug. Consider what happens if another process deletes the file between the call to isfile and the call to open.

    exceptions should be used much more sparingly in C++ than in Python because they don't work as well in the former.

    Could you explain what you mean by this? Is it that Python tends to throw (predictable) exceptions in cases where C++ has (unpredictable) undefined behavior?

  25. Re:As always, guidelines are for beginners by Darinbob · · Score: 3, Insightful

    I hate patterns. They're too much like verses from a religious text, because I've run across people who seem unable to understand your code unless it uses patterns from the official pattern Bible. Holding a conversation with them can involve being interrupted every few minutes with "oh, that's a FurblingFunctorFactory, why didn't you say so?" If you don't keep a close watch they'll go and changing existing/working code to rename classes to indicate what pattern they are.

  26. Re:As always, guidelines are for beginners by goose-incarnated · · Score: 2

    For C that's a perfectly reasonable use of goto. For C++ you should use unique_ptr or wrap your resource in your own object that you can stack allocate. RAII is a very nice pattern in C++.

    So unique_ptr will close open file handles and network connections?

    --
    I'm a minority race. Save your vitriol for white people.