SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
STL in C++
STL in C++STL in C++
STL in C++
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Effective c++ item49
Effective c++ item49Effective c++ item49
Effective c++ item49
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Android Jetpack
Android Jetpack Android Jetpack
Android Jetpack
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
Scanner class
Scanner classScanner class
Scanner class
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytest
 
Dynamic Polymorphism in C++
Dynamic Polymorphism in C++Dynamic Polymorphism in C++
Dynamic Polymorphism in C++
 

Destacado

Operator overloading
Operator overloadingOperator overloading
Operator overloading
Kamal Acharya
 

Destacado (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
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Similar a 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 a 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
 

Más de Richard Thomson

Más de 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
 

Último

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 

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