Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

C traps and pitfalls for C++ programmers

4,508 views

Published on

C++ provides backwards compatability with C, but you will have an easier time if you stay away from certain C-style programming habits. This presentation outlines traps and pitfalls from C style programming in C++ and recommends pure C++ alternatives that lead to fewer surprises, fewer errors and better code. This presentation hasn't been updated for C++11 and is based on C++03.

Published in: Software
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Discover a WEIRD trick I use to make over $3500 per month taking paid surveys online. read more... ◆◆◆ http://ishbv.com/surveys6/pdf
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • For C++ Certification Online Course Coupons and Discounts Visit http://www.todaycourses.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

C traps and pitfalls for C++ programmers

  1. 1. void *pointers  Loses all type information!  Should be avoided when possible  Make the C++ type system work for you, don’t subvert it  Interfaces to C libraries may require it
  2. 2. C Style Casts  C style casts:  do not communicate the intent of the cast  can give the wrong answer  Use relevant C++ casting operator  communicates the intent of the cast  gives the right answer  Use constructor syntax for values  int(floatFn()) instead of (int) floatFn()
  3. 3. const_cast<T>(expression)  const_cast<T> changes the const or volatile qualifier of its argument  With T const *p  use const_cast<T*>(p) instead of ((T *) p)  Declare class members mutable if they need to be updated from a const method  Writing through a reference or pointer stripped of its constness may cause undefined behavior!
  4. 4. static_cast<T>(expression)  Converts to type T, purely based on the types present in expression.  Use static_cast<T> when:  you intend that the cast does not require any run-time type information  Cast enums to a numeric type (int, float, etc.)  Cast from void pointer to T pointer  Cast across the class hierarchy with multiple inheritance; see http://www.sjbrown.co.uk/2004/05/01/always- use-static_cast/
  5. 5. dynamic_cast<T>(expressio n)  Requires RTTI to be enabled  Only for pointers or references  Returns 0 when object is not a T  Resolves multiple inheritance properly
  6. 6. reinterpret_cast<T>  The most evil of cast operators  Subverts the type system completely  Should only be needed when dealing with C style APIs that don’t use void pointers
  7. 7. Memory Allocation  Any call to new or new[] should only appear in a constructor  Any call to delete or delete[] should only appear in a destructor  Encapsulate memory management in a class
  8. 8. More on new and delete  new/new[]  does’t return 0 when memory is exhausted  throws bad_alloc  VC6 did it wrong; VS2005/gcc does it right  No need to check for zero pointer returned  delete/delete[]  Deleting a zero pointer is harmless  No need to check for zero pointer before calling  Always match new[] with delete[] and scalar new with scalar delete
  9. 9. Resource Acquisition  Memory is just one kind of resource  Others:  critical section  thread lock  etc  Treat identically to memory:  acquire resource in c’tor  release resource in d’tor  RAII – Resource Acquisition Is Initialization
  10. 10. Exceptions  Using RAII gives you exception safe code for free  Manual management of resources requires try/catch blocks to ensure no memory leaks when an exception is thrown
  11. 11. std::auto_ptr<T>  Takes ownership of whatever pointer assigned to it  ~auto_ptr() calls delete on the pointer  release() returns the pointer and releases ownership  Calls scalar delete; doesn’t work for arrays  Use for temporary buffers that are destroyed when going out of scope or are explicitly assigned to something else on success
  12. 12. std::vector<T>  Dynamically resizable array  Great for fixed-size buffers you need to create for C APIs when the size of the buffer is determined at runtime.  Use for temporary arrays of objects  If used as an array of pointers, it doesn’t call delete on each pointer
  13. 13. boost::shared_ptr<T>  Reference counted pointer  When reference count reaches zero, delete is called on the underlying pointer  Doesn’t guard against cycles  Can be good when used carefully, but can be bad when used excessively. It becomes hard to identify the lifetime of resources  See boost docs for more
  14. 14. boost::ptr_vector<T>  Boost container similar to std::vector<T>, but calls delete on each element when it is destroyed  See boost docs for more
  15. 15. C style strings  Don’t use them! Huge source of bugs.  Use a string class:  Qt’s QString  C++ std::string  C++ std::basic_string<TCHAR>  wxWidgets wxString  Pass string classes by const reference  Return string classes by value or through reference argument  Use std::string::c_str() to talk to C APIs
  16. 16. Use of void  Don’t use void argument lists:  Use void foo() instead of void foo(void)  Don’t use void pointers  It completely subverts the type system, leading to type errors
  17. 17. Callbacks  C code can only call back through a function pointer. A void pointer context value is usually passed along to the callback  C++ code uses an interface pointer or reference to communicate to its caller. No need to supply a context value as the interface pointer is associated with a class that will hold all the context.  Use interfaces instead of function pointers for callbacks
  18. 18. #define  Use enums to define groups of related integer constants  Use static const class members to define integer or floating-point values. Declare them in the .h, define them in the .cpp  Use inline functions or methods for small blocks of repeated code  Use templates as a way to write type safe macros that expand properly or generate a compiler error
  19. 19. Static Polymorphism  Static polymorphism exploits similarities at compile time  Dynamic polymorphism exploits similarities at runtime  Static polymorphism implemented with templates  Dynamic polymorphism implemented with virtual methods on classes
  20. 20. #if, #else, #endif  Used to express static variation in code  When compiled one way, you get one variation; when compiled the other way, you get the other variation  Better expressed through a template class that expresses the two variations as specifics of arguments to the template  Keeps syntactic checking on for both variations all the time

×