From C to Modern C++: Type, Resource, and Memory Safety
Working notes on the C++ language features that support safer types, object lifetimes, and resource management.
C#
is an amazing language that gives full control over hardware, however it comes with some limitations not limitations but like responsibilities and safety concernes such as memory leaks, double free, dangling pointers …
c++ which was introduced in 1983 by bjarne stroustrup, as not an alternative of c but a safer solutions specially for memory leaks by providing tools to avoid em.
what c++ have that c does not .#
object and type system .#
Lifetime and resource management .#
Generic and compile-time programming.#
Control flow and functions.#
Standard-library facilities.#
object and type system .#
- classes :
- classes are types while objects are intances of it .
- constructors :
- constructors types: default, parametrized, copy, move, conversion, delegating, inheriting, template .
- destructors :
- destruction types: standard destructor, virtual destructors, defaulted destructor, deleted destructor .
- access control:
- public, private, protected .
- inheritance:
- inheritance is is-a there is also composition has-a .
- virtual functions :
- a virtual function is a function inside the base classe that when inherrited it can be overrided by the derived classe, a virtual base function has it s adress, i mean the code is in code segment and loaded only once, if a derived function inherit it and do not override it will point to same chunk of code while if it override it it will have it s own chunk of code containing the overrided function, the vptr stays the same but the vtable entry instead of pointing to the base function will point to the adress of the new overrided function. [needed: vtable and vptr] .
- abstract classes:
- an abstract classe is a classe created only to be inherrited . and derived classes should override all of it s pure virtual functions but not data members (classe's variables), should have at least one pure virtual function (
= 0) and if a derived classe didnt override it that same classe will be abstract . and also abstract classes can't be instantiated .
- an abstract classe is a classe created only to be inherrited . and derived classes should override all of it s pure virtual functions but not data members (classe's variables), should have at least one pure virtual function (
- function overloading:
- function overloading is the ability to have multiple functions with the same name as long as they has either a different argument count , order, type and return type along is not enough.
- operator overloading:
- operator overloading is changing the behaviour of the operators (not all of em but most), limitations are a new operator cannot be created, can't change the args that an operator can take the arity. untouchable operators are :
':: <scope resolution>, . <member access>, .* <pointer to member access>, ?: <tenary conditional>, sizeof, typeid'.
- operator overloading is changing the behaviour of the operators (not all of em but most), limitations are a new operator cannot be created, can't change the args that an operator can take the arity. untouchable operators are :
- references
T&T&&:- references is two types,
&is a nickname of a variable and has permissionsint& refis rw whileconst int& refis readonly permission .T&&is a rvalue reference, it binds to temporaries (used for move) .
- references is two types,
- namesspaces:
- simply it s a scope to prevent conflits .
- stronger type conversions (casting) :
static_castthe normal casting,dynamic_castused when not sure of the type commonly in classes if it s the right type cast it if not returnnullptr, also works only on classes with virtual functions (the classe should have at least one virtual function), on non matching type; pointers givesnullptr, references throw errorstd::bad_cast.const_castremoves const from a pointer or reference with rules, a original declared const can be casted but modifying it is undefined behavior. while casted or turned to const but originally decalred normally can be safely casted to normal. use case :
- boolean
- true / false, under the hood it s c++ just a convertion (truthiness) 0 or
nullptrstored as false, 1 or any non-zero value is stored as true .
- true / false, under the hood it s c++ just a convertion (truthiness) 0 or
nullptr:- is a type safe littery a type
std::nullptr_talso in c++NULL= 0 which is traited as int, c storesNULLas((void*)0)a pointer .
- is a type safe littery a type
- enums :
- both traditional and c++ enum are stored as numbers, and both enum's type can be specified with a difference int traditional enums compiler decide the type while in c++ enums it default's to int making it clean . the difference is the scope . traditional enum's names leak to the surrounding scope while c++'s enums are scopped . the things that gives an ambigiouty such as math comparison because of the non safe type . along with forward declaration .
- Type aliases:
using- a shortcut or rename of an existing type (not creating a new type). used for code redability, no runtime cost.
- Runtime type information:
typeid,dynamic_cast:- both can inspect the type at runtime
Lifetime and resource management .#
first lifetime is the time between an intialization of a ressource till it s destroy or it s freeing. in c we use free() and others. c++ try to handle this automaticly by moving it into objects then the cleaning happens by itself.
- RAII (Ressource Aquisition Is Initialization)
- it s seen as a ressource is there. we can use it (allocate it) but we must give it back (deallocating it). it works by scopes, either a block of code contained in a scope a function or a classe. the contructor runs on initialization while the destructor runs when the program is out of that scope. (the thing here is that we did instantiate a classe use it s fields or methods multiple times does the compiler see the last time we used it then call the destructor after ?). but there is some exception that should be handled by good approaches such as exception at the middle of an initialization of a classe, let say we are instantiating a classe then an exception (error) happens in while the classe is still creating, so the destructor never runs because the object or the classe is traited as not created, and ressources allocated between the instantiating and the exception never freed or gived back. the fix here is to keep each ressource in each own RAII object, so when the exception occurs the ressource destructed before leaving the program.
class badapproach {
File* file; // initialization of a pointer.
int* buffer;
public:
badapproach(const std::string& filename) {
file = openFile(filename); // succefully getting the file
buffer = new int[1000]; // exception: outofmemory
// constructor abord
// badapproach never created so it's destructor never runs
// leading to a file leak `file` never freed
}
}- while keeping each ressource in it s object .
class goodaproach {
std::ifstream fileWrapper;
std::unique_ptr<int[]> bufferwrapper;
public:
goodapproach(const std::string& filename) // constructor signature
: fileWrapper(filename), // initialize
bufferWrapper(new int[1000]) // also
{
// if an exception occurs, std::ifstream and std::unique_ptr are objects so before exiting it s destructor will runs free the memory and nothing will be leaked.
}
}Note: the destructor runs on a reverse order, last created first destroyed.
new/delete- same principal as
mallocandfree, the difference is thatmallocallocate in memory andfreefree that memory, whilenewcall the constructor anddeletecalls the destructor. but it has same danger asmallocandfree, calling new then an exception occurs in the middle the instantiation of that classe or simply forgetting to calldeletewill lead to memory leak. double delete also wheredeleteis called twice trying to delete a free memory same as callingfreetwice. dangling pointers: a pointer trying to access a freed or destroyed data. the fix is to usestd::make_uniqueandstd::make_shared. - placement of new different than
new. not how to place new but choosing or deciding where that instatiated object will live. construct an object in a specifique place return the adress of that place to this pointer.
/* normal new */
Dog* d = new Dog(1); // instatiate dog and return it s adress to d.
delete d; // clean it up/* placement new */
Dog* d = new (place) Dog(1); // instatiate dog and place it in place then return the adress of that place to d.
d->~Dog(); // call the destructor to free the memory where the class lives.also the memory should be enough to fit the classe in. because it blindly trust you so not enough memory will lead to bugs crashes underfined behaviour.
- Rvalue and Lvalue references Lvalue is a normal variable has a name. while Rvalue are anonymous data dies the second that line of code finishes.
T&is for Lvalues whileT&&is for Rvalues.
void func(Buf& b); // copy the inside of b.
void func(Buff&& b); // steal what inside of b.
Buf f;
func(f); // f may be used later so we ll safely copy it.
func(Buf()); // Buf() has no name can't be called later. so steal it s data use it allocate memory.
func(std::move(f)); // a decision to take over f.
// also defining the function func twice is a correct c++ approach, handling rvalues and lvalues, the compiler decide based on the data passed. and also may have same logic i mean same internal or have different logic where lvalues. is traited differently than rvalues.
// another thing
void g(Buf&& b) {
Buf a = b; // b will be copied to c. because it has a name be may reuse b.
int c = std::move(b); // decision to move b.
}- Move semantics
move semantics is as simple as copying few bytes containing the adress it points to then assigning nullptr to the old one .// in c
int b = 145;
int* a = &b;
int* c = a;
a = NULL;
// in c++
std::unique_ptr<int> a = std::make_unique<int>(145); // creating a unique pointer to the chunk in ram containing 145;
std::unique_ptr<int> b = std::move(a); // moving the ownership of that chunk, a is setted to nullptr means freed.[@AbstractClassCppreferencecom] [@Const_castConversionCppreferencecom] [@CppTypesBad] [@Dynamic_castConversionCppreferencecom] [@EnumerationDeclarationCppreferencecom] [@Dynamic_castConversionCppreferencecoma] [@StdBad_castCppreferencecom] [@stroustrupAddingClassesLanguage1983]