SlideShare a Scribd company logo
1 of 21
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

C++ Pointers And References
C++ Pointers And ReferencesC++ Pointers And References
C++ Pointers And References
verisan
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
abhay singh
 

What's hot (20)

C++ Pointers And References
C++ Pointers And ReferencesC++ Pointers And References
C++ Pointers And References
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
 
Functions in C
Functions in CFunctions in C
Functions in C
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
 
Python
PythonPython
Python
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
Pointers
PointersPointers
Pointers
 

Viewers also liked

Operator overloading
Operator overloadingOperator overloading
Operator overloading
Kamal Acharya
 
Introduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSAIntroduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSA
Nikesh Mistry
 

Viewers also liked (20)

Gérer son environnement de développement avec Docker
Gérer son environnement de développement avec DockerGérer son environnement de développement avec Docker
Gérer son environnement de développement avec Docker
 
Effective stl notes
Effective stl notesEffective stl notes
Effective stl notes
 
Effective c++notes
Effective c++notesEffective c++notes
Effective c++notes
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
BEFLIX
BEFLIXBEFLIX
BEFLIX
 
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий Леванов
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
STL Algorithms In Action
STL Algorithms In ActionSTL Algorithms In Action
STL Algorithms In Action
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
File Pointers
File PointersFile Pointers
File Pointers
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Introduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSAIntroduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSA
 

Similar to C traps and pitfalls for C++ programmers

434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
MAHESHV559910
 
02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados
Tiago Romão
 

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

434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
C# basics
 C# basics C# basics
C# basics
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados
 
The c++coreguidelinesforsavercode
The c++coreguidelinesforsavercodeThe c++coreguidelinesforsavercode
The c++coreguidelinesforsavercode
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
 
core java
 core java core java
core java
 
c# at f#
c# at f#c# at f#
c# at f#
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
 
Introduction toc sharp
Introduction toc sharpIntroduction toc sharp
Introduction toc sharp
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# Programming
 

More from Richard Thomson

More from Richard Thomson (8)

Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdfVintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
 
Automated Testing with CMake, CTest and CDash
Automated Testing with CMake, CTest and CDashAutomated Testing with CMake, CTest and CDash
Automated Testing with CMake, CTest and CDash
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
 
Consuming Libraries with CMake
Consuming Libraries with CMakeConsuming Libraries with CMake
Consuming Libraries with CMake
 
SIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler IntrinsicsSIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler Intrinsics
 
Cross Platform Mobile Development with Visual Studio 2015 and C++
Cross Platform Mobile Development with Visual Studio 2015 and C++Cross Platform Mobile Development with Visual Studio 2015 and C++
Cross Platform Mobile Development with Visual Studio 2015 and C++
 
Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++
 
Web mashups with NodeJS
Web mashups with NodeJSWeb mashups with NodeJS
Web mashups with NodeJS
 

Recently uploaded

Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
drm1699
 

Recently uploaded (20)

GraphSummit Milan - Neo4j: The Art of the Possible with Graph
GraphSummit Milan - Neo4j: The Art of the Possible with GraphGraphSummit Milan - Neo4j: The Art of the Possible with Graph
GraphSummit Milan - Neo4j: The Art of the Possible with Graph
 
GraphSummit Milan - Visione e roadmap del prodotto Neo4j
GraphSummit Milan - Visione e roadmap del prodotto Neo4jGraphSummit Milan - Visione e roadmap del prodotto Neo4j
GraphSummit Milan - Visione e roadmap del prodotto Neo4j
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale IbridaUNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
 
Workshop - Architecting Innovative Graph Applications- GraphSummit Milan
Workshop -  Architecting Innovative Graph Applications- GraphSummit MilanWorkshop -  Architecting Innovative Graph Applications- GraphSummit Milan
Workshop - Architecting Innovative Graph Applications- GraphSummit Milan
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Novo Nordisk: When Knowledge Graphs meet LLMs
Novo Nordisk: When Knowledge Graphs meet LLMsNovo Nordisk: When Knowledge Graphs meet LLMs
Novo Nordisk: When Knowledge Graphs meet LLMs
 
Rapidoform for Modern Form Building and Insights
Rapidoform for Modern Form Building and InsightsRapidoform for Modern Form Building and Insights
Rapidoform for Modern Form Building and Insights
 
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
 
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
 
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
 
Encryption Recap: A Refresher on Key Concepts
Encryption Recap: A Refresher on Key ConceptsEncryption Recap: A Refresher on Key Concepts
Encryption Recap: A Refresher on Key Concepts
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with Links
 

C traps and pitfalls for C++ programmers

  • 1.
  • 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