SlideShare a Scribd company logo
4
Most read
9
Most read
16
Most read
C traps and pitfalls for C++ programmers
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
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()
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!
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/
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
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
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
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
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
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
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
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
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
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
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
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
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
#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
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
#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

More Related Content

What's hot (20)

PDF
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
Seok-joon Yun
 
PPTX
Pointers in c - Mohammad Salman
MohammadSalman129
 
PDF
Chapitre 02 : Variables, Expressions et Instructions
L’Université Hassan 1er Settat
 
PPTX
Types of function call
ArijitDhali
 
PDF
マーク&スイープ勉強会
7shi
 
PPTX
Dynamic memory allocation
Burhanuddin Kapadia
 
PPT
C pointers
Aravind Mohan
 
PDF
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PPTX
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
PPT
Lect 1-class and object
Fajar Baskoro
 
PPTX
Structure & union
Rupesh Mishra
 
PPTX
Structures in c language
Tanmay Modi
 
PPTX
python
aimas06
 
PDF
Data Structures
Prof. Dr. K. Adisesha
 
PDF
Pointers and Structures
Gem WeBlog
 
PPT
Pointers in c
Mohd Arif
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPTX
Main method in java
Hitesh Kumar
 
PDF
Processeur
IDriss Yassine
 
PPTX
Pointers in C
Kamal Acharya
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
Seok-joon Yun
 
Pointers in c - Mohammad Salman
MohammadSalman129
 
Chapitre 02 : Variables, Expressions et Instructions
L’Université Hassan 1er Settat
 
Types of function call
ArijitDhali
 
マーク&スイープ勉強会
7shi
 
Dynamic memory allocation
Burhanuddin Kapadia
 
C pointers
Aravind Mohan
 
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Lect 1-class and object
Fajar Baskoro
 
Structure & union
Rupesh Mishra
 
Structures in c language
Tanmay Modi
 
python
aimas06
 
Data Structures
Prof. Dr. K. Adisesha
 
Pointers and Structures
Gem WeBlog
 
Pointers in c
Mohd Arif
 
Pointer in C++
Mauryasuraj98
 
Main method in java
Hitesh Kumar
 
Processeur
IDriss Yassine
 
Pointers in C
Kamal Acharya
 

Viewers also liked (20)

PDF
Gérer son environnement de développement avec Docker
Julien Dubois
 
PDF
Effective stl notes
Uttam Gandhi
 
PPT
Intro. to prog. c++
KurdGul
 
PPTX
BEFLIX
Richard Thomson
 
PDF
Smart Pointers
Roman Okolovich
 
PPTX
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Yandex
 
PDF
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
PPTX
Dependency Injection in C++ (Community Days 2015)
Daniele Pallastrelli
 
PPTX
С++ without new and delete
Platonov Sergey
 
PPTX
Михаил Матросов, “С++ без new и delete”
Platonov Sergey
 
PPTX
Operator Overloading
Dustin Chase
 
PDF
STL Algorithms In Action
Northwest C++ Users' Group
 
PPTX
C++ Dependency Management 2.0
Patrick Charrier
 
ODP
Multithreading 101
Tim Penhey
 
PDF
C++11 smart pointers
chchwy Chang
 
PPT
Memory Management In C++
ShriKant Vashishtha
 
PDF
Operator overloading
Kamal Acharya
 
PDF
Introduction to Bitcoin and ECDSA
Nikesh Mistry
 
PDF
Multithreading done right
Platonov Sergey
 
Gérer son environnement de développement avec Docker
Julien Dubois
 
Effective stl notes
Uttam Gandhi
 
Intro. to prog. c++
KurdGul
 
Smart Pointers
Roman Okolovich
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Yandex
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Dependency Injection in C++ (Community Days 2015)
Daniele Pallastrelli
 
С++ without new and delete
Platonov Sergey
 
Михаил Матросов, “С++ без new и delete”
Platonov Sergey
 
Operator Overloading
Dustin Chase
 
STL Algorithms In Action
Northwest C++ Users' Group
 
C++ Dependency Management 2.0
Patrick Charrier
 
Multithreading 101
Tim Penhey
 
C++11 smart pointers
chchwy Chang
 
Memory Management In C++
ShriKant Vashishtha
 
Operator overloading
Kamal Acharya
 
Introduction to Bitcoin and ECDSA
Nikesh Mistry
 
Multithreading done right
Platonov Sergey
 
Ad

Similar to C traps and pitfalls for C++ programmers (20)

PDF
Bjarne essencegn13
Hunde Gurmessa
 
PPT
Advance features of C++
vidyamittal
 
PPT
Cppt 101102014428-phpapp01
Getachew Ganfur
 
PDF
C++ Training
SubhendraBasu5
 
PPTX
C++ Introduction brown bag
Jacob Green
 
PPTX
Return of c++
Yongwei Wu
 
PPTX
C++ idioms.pptx
Janani Anbarasan
 
PPTX
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
PPTX
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
PDF
The c++coreguidelinesforsavercode
Divyang Panchasara
 
PDF
How to make a large C++-code base manageable
corehard_by
 
PPTX
Modern C++ Lunch and Learn
Paul Irwin
 
PDF
Effective Object Oriented Design in Cpp
CodeOps Technologies LLP
 
PDF
Cs tocpp a-somewhatshortguide
Alex Popov
 
PDF
CS225_Prelecture_Notes 2nd
Edward Chen
 
PDF
00-intro-to-classes.pdf
TamiratDejene1
 
DOC
Uop gsp 125 final exam guide new
ElijahEthaan
 
PPTX
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
 
PPT
lecture02-cpp.ppt
DevliNeeraj
 
PPT
lecture02-cpp.ppt
ssuser0c24d5
 
Bjarne essencegn13
Hunde Gurmessa
 
Advance features of C++
vidyamittal
 
Cppt 101102014428-phpapp01
Getachew Ganfur
 
C++ Training
SubhendraBasu5
 
C++ Introduction brown bag
Jacob Green
 
Return of c++
Yongwei Wu
 
C++ idioms.pptx
Janani Anbarasan
 
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
The c++coreguidelinesforsavercode
Divyang Panchasara
 
How to make a large C++-code base manageable
corehard_by
 
Modern C++ Lunch and Learn
Paul Irwin
 
Effective Object Oriented Design in Cpp
CodeOps Technologies LLP
 
Cs tocpp a-somewhatshortguide
Alex Popov
 
CS225_Prelecture_Notes 2nd
Edward Chen
 
00-intro-to-classes.pdf
TamiratDejene1
 
Uop gsp 125 final exam guide new
ElijahEthaan
 
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
 
lecture02-cpp.ppt
DevliNeeraj
 
lecture02-cpp.ppt
ssuser0c24d5
 
Ad

More from Richard Thomson (9)

PPTX
Why I Use Visual Studio & ReSharper for C++
Richard Thomson
 
PDF
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Richard Thomson
 
PPTX
Automated Testing with CMake, CTest and CDash
Richard Thomson
 
PPTX
Feature and platform testing with CMake
Richard Thomson
 
PPTX
Consuming Libraries with CMake
Richard Thomson
 
PPTX
SIMD Processing Using Compiler Intrinsics
Richard Thomson
 
PPTX
Cross Platform Mobile Development with Visual Studio 2015 and C++
Richard Thomson
 
PDF
Consuming and Creating Libraries in C++
Richard Thomson
 
PPTX
Web mashups with NodeJS
Richard Thomson
 
Why I Use Visual Studio & ReSharper for C++
Richard Thomson
 
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Richard Thomson
 
Automated Testing with CMake, CTest and CDash
Richard Thomson
 
Feature and platform testing with CMake
Richard Thomson
 
Consuming Libraries with CMake
Richard Thomson
 
SIMD Processing Using Compiler Intrinsics
Richard Thomson
 
Cross Platform Mobile Development with Visual Studio 2015 and C++
Richard Thomson
 
Consuming and Creating Libraries in C++
Richard Thomson
 
Web mashups with NodeJS
Richard Thomson
 

Recently uploaded (20)

PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Human Resources Information System (HRIS)
Amity University, Patna
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 

C traps and pitfalls for C++ programmers

  • 2. 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
  • 3. 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()
  • 4. 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!
  • 5. 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/
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. #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
  • 20. 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
  • 21. #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