Working Notes: a commonplace notebook for recording & exploring ideas.
Home. Site Map. Subscribe. More at expLog.
— Kunal
Modern C++ 19-07-2016
can control and have abstraction
should depends
weak exception safety
noexceptdon’t use any other exception specifiers
can still use noexcept
will force a death if things throw
be careful about ownership, memleak, locks, file descriptors
write cleanup stanzas
idiomatic c code
Wikipedia
Resource Acquisition is Initialization
Constructors acquire a resource
Destructors clean up a resource
folly scopeGuard
folly::FILE is an RAII type that closes the file on destruction
Never write delete
Classes with business logic should compose RAII
- C pointers =int foo(MyStruct* o)=
- Read only
- use const
- optional
- =folly::optional=, =std::optional=
- it's okay for optional
- mutable
- in/out parameter: stl does it by =int foo(MyStruct& o)=
- transfer/Object sinks
- unique_ptr
- or return pointers
- return a unique pointer
RAII => Object lifetime = resource lifetime
Resolving ownership solves lifetime problems
Get the ownership model of the code correct
unique_ptr
shared_ptr
shared_ptr is not thread safe:
std::atomicconst means object isn’t modified
claiming (complete/shared) ownership means that the object is modified
own
never write new, only in factory-only functions
std::make_shared creates a new object, and sets up the shared
pointer
folly::make_unique
don’t write your own
folly mpmcqueue, synchronized, futures
make a different abstraction
lots of basic primitives
std::atomic
volatile
std::atomic boolLocks
Polymorphism
virtual
fake virtual
static polymorphism
actual C++ iterators
templates
virtual
std::function: dynamically polymorphic, can’t inline
lambdas are statically polymorphic
pass lambdas directly
templates are basically duck typing; will just punch you with a compiler error.
reference type or a value type?
explicit if you are a single argument constructor; allows for
implicit conversion from argument to parent type
never two phase initialize
constructors
is it copyable? movable?
never write your own copy constructor
never write your own destructor
const correctness
Ok
class Object {
Object(Object& object) = delete;
}
free function that works on views that do real work wrapper function that allocates memory, resources objects wrap this
containers are one thing, algorithms are another thing