Skip to content

Latest commit

 

History

History

Miscellaneous

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Miscellaneous

This directory contains miscellaneous code when self-learning concepts in C++.
Python and Rust code are migrated to independent repository.


Handy Notes - C++ Concepts and Best Practices

System-wise Memory Allocation

Different memory allocations grant data different lifetimes.
There are 4 different memory partitions in execution:

  • Source code: read-only and shared binary file generated by compiler
    • compile time
    • read-only: prevent writing access while executing .exe
    • shared: only contains one instance of executable file
  • Global: static variables and functions
    • compile time
    • consts, const strings, statics and others
      (constant global/scoped variables)
    • managed by compiler
  • Stack: contains data managed by compiler
  • Heap: contains data managed by developer

Static VS. Dynamic Memory Allocation

  • Static: compile-time, stored in Stack
  • Dynamic: run-time, stored in heap

Do Not Return References to Local Variables on Stack

#include <iostream>

/* Returning a pointer to a local stack variable is bad practice. */
int* func() {
  int a = 10;
  return &a; // void pointer will be yield
} // variable a goes out of scope, deleted by Compiler

int main(void) {
  int* p = func();
  std::cout << *p << "\n"; // OK; reserved by compiler
  std::cout << *p << "\n"; // ERROR without exception! void pointer

  system("pause");
  return 0;
}

auto x = {11, 23, 9}; // x is of type std::initializer_list<int>

template<typename T>
void f(T param);

f({11, 23, 9}); // error: can't deduce type for T

Consider the following instead

template<typename T>
void f(std::innitializer<T> initList);

f({11, 23, 9}); // T is deducted as int, and initList's type is std::initializer_list<int>