More Related Content
Similar to C++ Tips for Java Programmers (JavaZone 2017) (20)
More from Patricia Aas (20)
C++ Tips for Java Programmers (JavaZone 2017)
- 1. C++ Tips for Java Programmers
Memory
● Never ever new anything
● Never explicitly delete anything
● Use the stack/scope to control your object lifetimes
● Use value objects for almost all of your ownership
● Only use unique_ptr<> when you have to transfer ownership
● Only use shared_ptr<> if you are really going to share (and do you really need to?
Really?)
● Try to use std::make_unique when constructing objects for the unique_ptr
● Try to use std::make_shared when constructing objects for the shared_ptr
● Never use char* - use std::string
● Never use array[]
● Prefer std::vector to most data structures (or std::array)
● Only use other data structures if you need them - and don’t make up your own, use
composition/adaptor pattern
Class design
● Prefer to define at most the constructor (rule-of-zero) for the majority of your classes :
design your classes so that the default predefined functions work well
● If you need any more than just the constructor then the class should be focused
exclusively on ownership
Parameters/Return value
● As a rule parameters are either references or values
● If a parameter could be null then pointer is acceptable (should be the exception)
● Pass everything non-trivial as a reference - const if you can
● Possibly pass trivial stuff by value especially if they might take a copy
● Prefer return by value
● Use const as much as possible
● As a rule pass smart pointers by reference - unless participating in the object lifetime or
ownership
● Don’t have default values for parameters in virtual functions
● Use std:pair or std:tuple to return multiple values
Functions
● Make all getters const
● Avoid having complex objects as static in a function
- 2. Inheritance
● Prefer pure virtual if you need to specify an interface
● Always use override for overridden functions (and drop virtual)
● Never call a virtual function in a Constructor or a Destructor
● Any class with a virtual function needs a virtual Destructor
Object construction
● Initialize all members, always!
● Try to initiate all the members you can in the header
● Only initialize the ones depending on constructor parameters in the constructor list.
● Initialize these in the order specified in the header
● Try to always have an empty body in the constructor, it shouldn't do anything interesting
Constructs
● Prefer range based for
● Use std algorithms when appropriate
● Never use goto
● Use nullptr for null
● Use namespaces to represent packages
General
● Heed your compiler warnings
● Don’t use macros
● Beware of integer overflow
● Ask for help