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

C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Rahul Jamwal
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
Philip Schwarz
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 
String c
String cString c
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Burhanuddin Kapadia
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
khush_boo31
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
Philip Schwarz
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Coding standard
Coding standardCoding standard
Coding standard
Shwetketu Rastogi
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
Abhilash Nair
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
sandeep54552
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
Ravi_Kant_Sahu
 
Files in C
Files in CFiles in C
Files in C
Prabu U
 
Fundamentos C++
Fundamentos C++Fundamentos C++
Fundamentos C++
Edgar Merino
 

What's hot (20)

C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
String c
String cString c
String c
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Coding standard
Coding standardCoding standard
Coding standard
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Files in C
Files in CFiles in C
Files in C
 
Fundamentos C++
Fundamentos C++Fundamentos C++
Fundamentos C++
 

Viewers also liked

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
Julien Dubois
 
Effective stl notes
Effective stl notesEffective stl notes
Effective stl notes
Uttam Gandhi
 
Effective c++notes
Effective c++notesEffective c++notes
Effective c++notes
Uttam Gandhi
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
KurdGul
 
BEFLIX
BEFLIXBEFLIX
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
Roman Okolovich
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Yandex
 
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)
Ovidiu Farauanu
 
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)
Daniele Pallastrelli
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
Platonov Sergey
 
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())
Sameer Rathoud
 
Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”
Platonov Sergey
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Dustin Chase
 
STL Algorithms In Action
STL Algorithms In ActionSTL Algorithms In Action
STL Algorithms In Action
Northwest C++ Users' Group
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0
Patrick Charrier
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
Tim Penhey
 
File Pointers
File PointersFile Pointers
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
chchwy Chang
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Kamal Acharya
 

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

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
 
C# basics
 C# basics C# basics
C# basics
Dinesh kumar
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
ssusera0bb35
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
Abed Bukhari
 
C++ Training
C++ TrainingC++ Training
C++ Training
SubhendraBasu5
 
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
 
The c++coreguidelinesforsavercode
The c++coreguidelinesforsavercodeThe c++coreguidelinesforsavercode
The c++coreguidelinesforsavercode
Divyang Panchasara
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
ppd1961
 
core java
 core java core java
core java
dssreenath
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
Harry Balois
 
c# at f#
c# at f#c# at f#
c# at f#
Harry Balois
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
Mahmoud Ouf
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
RishikaRuhela
 
Introduction toc sharp
Introduction toc sharpIntroduction toc sharp
Introduction toc sharp
SDFG5
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
ReemaAsker1
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
ReemaAsker1
 
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
Rasan Samarasinghe
 
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
Apache Traffic Server
 
Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# Programming
Bhushan Mulmule
 

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# AND F#
C# AND F#C# AND F#
C# AND F#
 
c# at f#
c# at f#c# at f#
c# at 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

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
Richard Thomson
 
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
Richard Thomson
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
Richard Thomson
 
Consuming Libraries with CMake
Consuming Libraries with CMakeConsuming Libraries with CMake
Consuming Libraries with CMake
Richard Thomson
 
SIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler IntrinsicsSIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler Intrinsics
Richard Thomson
 
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++
Richard Thomson
 
Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++
Richard Thomson
 
Web mashups with NodeJS
Web mashups with NodeJSWeb mashups with NodeJS
Web mashups with NodeJS
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

Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
shanihomely
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
HIRE A HACKER FOR CHEATING HUSBAND/WIFE)
HIRE A HACKER FOR CHEATING HUSBAND/WIFE)HIRE A HACKER FOR CHEATING HUSBAND/WIFE)
HIRE A HACKER FOR CHEATING HUSBAND/WIFE)
josephinedrea942
 
Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...
Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...
Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...
revolutionary575
 
Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...
Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...
Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...
bhumivarma35300
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
Task Tracker
 
當測試開始左移
當測試開始左移當測試開始左移
當測試開始左移
Jersey (CHE-PING) Su
 
welcome to presentation on Google Apps
welcome to   presentation on Google Appswelcome to   presentation on Google Apps
welcome to presentation on Google Apps
AsifKarimJim
 
11 Top Cross Browser Testing Tools to Know About.pdf
11 Top Cross Browser Testing Tools to Know About.pdf11 Top Cross Browser Testing Tools to Know About.pdf
11 Top Cross Browser Testing Tools to Know About.pdf
kalichargn70th171
 
Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...
Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...
Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...
kiara pandey
 
Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.
shivamt017
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
ThousandEyes
 
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
rachitkumar09887
 
React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
SSTech System
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
miso_uam
 
Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...
Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...
Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...
OnePlan Solutions
 
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Deliverybangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
ashiklo9823
 
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
902basic
 

Recently uploaded (20)

Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
HIRE A HACKER FOR CHEATING HUSBAND/WIFE)
HIRE A HACKER FOR CHEATING HUSBAND/WIFE)HIRE A HACKER FOR CHEATING HUSBAND/WIFE)
HIRE A HACKER FOR CHEATING HUSBAND/WIFE)
 
Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...
Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...
Busty Girls Call Mumbai 9930245274 Unlimited Short Providing Girls Service Av...
 
Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
 
Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...
Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...
Independent Girls call Service Pune 000XX00000 Provide Best And Top Girl Serv...
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
 
當測試開始左移
當測試開始左移當測試開始左移
當測試開始左移
 
welcome to presentation on Google Apps
welcome to   presentation on Google Appswelcome to   presentation on Google Apps
welcome to presentation on Google Apps
 
11 Top Cross Browser Testing Tools to Know About.pdf
11 Top Cross Browser Testing Tools to Know About.pdf11 Top Cross Browser Testing Tools to Know About.pdf
11 Top Cross Browser Testing Tools to Know About.pdf
 
Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...
Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...
Celebrity Girls Call Mumbai 9930687706 Unlimited Short Providing Girls Servic...
 
Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
 
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
 
React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
 
Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...
Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...
Maximizing Efficiency and Profitability: Optimizing Data Systems, Enhancing C...
 
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Deliverybangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
 
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
 

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