0%

Modern C++ Learning

1. String

  • \n and endl?
  • Use \n for general
  • endl for flush the output and immediately visible
  • using: can be in different level
  • Used as alias
  • Cout? cerr? Buffer or not

String could be see as a read-only array with zero terminator, so the “Hello” is 6 byte rather than 5

2. Variable

Static type

Variable could be declared or assigned multiple times, but only define once

  • Heap? Stack?
  • Stack for local varariable and function call frame
  • Heap for dynamic data

define array

1
int a[]={1,2,3,...}
  • size_t: represent the maximum size of any object
  • float should be noted as 0.f as example
  • byte 8 bit, unsigned char 8 bit, but the byte can only take bitwise operation
  • :: would use the global varaiable
  • thread_local and static
  • use const

Reference

  • Left-value
  • right-value: an alias

Const

  • const
  • Constexpr: more strict, more performance, don’t need to calculte in run time

3. Function

Parameter by reference

  • The & is used to create a alias

Forward declarations

  • return type, function name and types

Multiple definition of function with same name, but the parameters are different type

  • Static local, NOT thread-safe

Return with auto, structured binding

1
2
3
return std::pair{a,b}
auto [a,b]=..

Inline function: remove the the time overhead of a function call

  • best for very short function

No returning

  • Std::terminate(), but the memory is not freed
  • [[noreturn]], may be more optimization
  • Useful when function would terminate the program

4. Array

Lvalue, rvalue

  • lvalue is just an alias, but to a defined data
  • rvalue, the lvalue of a temporary object

Pointer: a 64bit value, works on typed or untyped data

1
2
const char* p=str;
// Actuarry is "const char*" and "p", means the p is a pointer to const string

Traversal array: compare address

1
for(auto p=begin(numbers);p!=end(numbers);p++)
  • reverse order: rbegin, rend

5. Enum

Why enum? commonly a set of named integer?

  • give name to integer, more readable and self-explanatory

Struct: composite types, instantance of struct called object

  • benefit: more intuitive, value would be init as 0
1
2
3
4
5
6
//inheritance or composition
struct Pixel: Point {
}
struct Pixel {
Point x;
}

Struct and Class? almost the same, just preference

  • default accessibility: struct public, class private
  • inheritance: struct public, class private

6. Data Structure

String

  • Std::string, concatenation, indexing, sub-string, comparison
  • Use .at for checked selection
  • insert, erase, replace, substr
  • to_string()
  • stoi, stol..

String_views: can be constructed and passed more cheaply

  • read only
  • use when you want performance

Vector

  • Std::vector
  • Sort(begin(v),end(v))
  • Many function to use,
  • Push_back, pop_back, front, back, at, resize

Span: differnt data structure version of string_view

  • name from math world
  • can be used with array, vector, string

Sets: ordered or unordered

  • fast lookup

List: for insertion and erase for better performance

  • forward list, single direction linked list

Maps: contain pair for key and value

1
2
3
4
5
map<string,double> products{
{ "Apples", 0.65 },
{ "Oranges", 0.85 },
{ "Bananas", 0.45 },
{ "Pears", 0.50 }

Vector

7. File

1
2
3
4
5
6
ifstream infile;
int c = infile.get();
while (c != ifstream::traits_type::eof()) {
cout << static_cast<char>(c);
c = infile.get();
}
  • sanity check eol end of file
  • File are just like stream

Getline(cin,s) would dynamically collect the memory

8. Class

constructor

  • protect, private
  • private is only this class
  • protected can be accessed by subclass
  • Virtual: a base function that can be overriden
  • if not, the base function would be called

Deconstructor

  • objects allocated using new is on heap, so won’t be deleted if explicitly delete
  • =delete is used to prevent unwanted unwanted operation

Friend functions and classes

  • have access to private and protected

Polymorphism

  • derived class can be manipulated as a base class

  • if declared with virtual, the function used would be selected in run-time

1
2
3
4
virtual f(); //normal
virtual f()=0; //must be override
virtual f() override; // is override previous
virtual f() override final; // no more override

Abstract class: if contain a pure virtual function (has no implementation)

9. Templates

Types as parameters

1
vector<double> vd

in fact, STD does NOT contain a specialization of vector for double, is is generated by compiler.

Use std::optional to provide more safety check for maybe null ptr

Explicit: the compiler would not perform implicit conversion

10. Exception

Try and Catch,

... can take any thing

for_each(begin, end, ref(f))

  • Ref make a reference, so no object is copyed

11. Lambda

1
auto l=[](){}

Use with std algorithm like for_each and sort etc

[] capture the data

if [&], then the data in main() could be accessed, by reference

if [=], accessed by value

12. Smart Pointers

Entities behind heap object

  • unique_ptr: exculsive ownership, only the object
  • Shared_ptr: become reference counted, only delete it when the last pointer goes out of scope
  • weak_ptr: have access right but don’t affect the life time

13. Takeaway

[[noreturn]] for termination

[[noexcept]] for performance and better memory usage