C/C++ Language Basic
Simple Concepts
Reference & Pointer
- Reference <=> alias, the variable stands for a address
- Pointer, the variable save the address
Overload & Override
- Overload: just same name with same return type.
- Override:can only be done in derived class
What will run before calling main
- static or global constructor
Array & Pointer
1 | char a[] = “hello”; |
Function Pointer
int (*s[10])(int)
stands for a function pointer array, each element is a pointer to a function with pattern int func(int param)
Direct Address Use
1 | // assign 1234(int) on address 0x100000 |
const , define, static, enum
- const
- behavior:always let the right part to be fixed
const char* p
=char const *p
=> can’t not modify*p
char* cosnt p
=> can’t not modifyp
- storage:
- global constants => read only data (generated by compiler)
- local constants => stack
- const function body implementation: take the
this
pointer as a const pointer.
- behavior:always let the right part to be fixed
- static
- determines the lifetime and linkage of the variable
- define
- preprocessing before compiling, replace the code
- define vs const
const
provides type checkingdefine
no extra space
- enum
- Enum variable actually is a integer in memory. There is no enums when code runs. It’s just a semi-type-safe form of #define
- Size: often 4 bytes, but the standard does not say what size it should be; only that it should be big enough to fit any enumerator.
Object Oriented vs Procedure Oriented
- POP:
- divides program into small parts called functions
- separates data and method
- OOP:
- Encapsulation(class) => Data hiding(private) and Bundling of data and methods together
- Inheritance => code reuse
- Polymorphism
static vs global
C
- sameness
- variables stay in .bss(uninitialized) or .data(initialized) segment
- could be accessed if included
- difference
- static :
- variables can be defined in function
- has static (internel) linkage
- global:
- has externel linkage (other file could access by
externel
)
- has externel linkage (other file could access by
- static :
C++
- static could declared in class but must be initilized in out of calss.
- static variable in class belong to the class.
- static function can not use
this
Memory: new, delete, malloc, free
malloc
,free
- What: std lib function
- Behavior: only allocate/free the space
- Return: void*
- Failure: return NULL
- Memory allocated from: heap
- Size: need a manual calculation
new
,delete
- C++ operator, could be overrided
- allocate/free the space first, and call constructor and destructor
- Return: a exact type pointer
- Failure: throw a exception
- Memory allocated from : free store
- Size: calculated by compiler ( =
sizeof(type)
, called with a TYPE-ID) - Reallocation: not provided (because of copy constructor)
- Implementation
some tricks:
free store
andheap
are the same thing from the machine’s point of view- in-place
new
to avoid operate memory1
2
3A* a = new A;
a.~A() // call destructor but not free the space
a = new (a) A; // call constructor on address a - sizeof(empty struct) = 1. Beacuase std define new could only
Polymorphism 多态
There is a hierarchy of classed and they are related by inheritance.
- dependency: inheritance and function override
- abstart: the ability of a object to be used in more than one form.
- specific: a call to a member function will cause a different function to be executed depending on the type of object.
Compile time Polymorphism
- early binding
- designed for function reuse
- sub(derived,child) class function replace the super(base) class function
Why use Constructor member initialization list
init before running the function body
- Efficiency
- Initialization of base class
- Initialization of Subobjects which only have parameterized constructors
- Initializing non-static const data members
- Initialization of reference data members
Runtime Polymorphism
- late binding
- dependency: inheritance and virtual function override
- call function of derived class
- In many cases, deconstructor should be virtual
- To avoid memory leak, because deleting objects of base type will not call the deconstructor of derived class.
Pure Virtual Functions <=> interface
Implementation
add a constant virtual table vtable
and a member function pointer vptr
for each class.
vtable
: A table of function pointers.- maintained per class by compiler.
vptr
: A pointer to vtable.- maintained per object.
- maintained per object.
Addition: What does compiler do?
- insert a code to every constructor: set
vptr
tovtable
of the associated class - change the function call to vitual function: first
vtable
according tovptr
, and then access the target function.
- insert a code to every constructor: set
so the virtual function call is a bit slower than the normal function
STL
vector
maintain a array with dynamic size inside
- you’d better reserve if you know the max size
- will double capacity if the size is greater than capacity
- access:
[]
do not check range,at()
will check range clear()
do not free space- space-optimization(bitmap) for bool, can use uint8_t to avoid space-optimization. 不考虑缓存的情况下空间优化会导致性能下降
map red-black tree
unordered_map hash
- structure array + bucket(link list to hanlde hash conflict)
- enlarge capacity( need rehash) allocate a larger space and reinsert its items
When Capacity Change for C++11
1 | if type of item defines the right value reference(&&) constuctor |
Noteworthy Features of C++11
smart pointer
- shared_pointer
- use
- unique_pointer
- weak_pointer
- not change reference counter
- automatic release is not supported
move & rvalue reference
Standard Library
x`
Grammar Improvement
lambda
- alias : anonymous function
- format: capture->return-type {body}
auto & decltype
- Automatic Type Deduction
- Auto
1
2
3
4
5
6auto x=0; //x has type int because 0 is int
auto c='a'; //char
auto d=0.5; //double
auto national_debt=14400000000000LL;//long long
vector<int> v;
auto iter=v.begin(); //vector<int>::iterator - Decltype (typedef according to the type of an object or an expression)
1
2
3
4const vector<int> vi;
typedef decltype (vi.begin()) CIT;
CIT iter2;
Deleted and Default Functions
- often used with multiple constructors
- could set default function or delete some function
nullptr
replace NULL
override
Reference
Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
TODO What is the use of volatile qualifier in C? https://www.quora.com/What-is-the-use-of-volatile-qualifier-in-C https://barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword~~