me
Superdanby
2019/01/05 @ C++

C++ Notes

C C++

Important Concepts

Rvalue Reference

Value Category

constexpr

  • constexpr vs const: constexpr variables will be evaluated in compile time while const variables may be evaluated in compile time or runtime.
  • checking with noexcept

List Initialization

Array declaration

Read array declarations from inside to outside

1
2
3
4
5
int *ptrs[10];            //  ptrs is an array of ten pointers to int
int &refs[10] = /* ? */;  //  error: no arrays of references
int (*Parray)[10] = &arr; //  Parray points to an array of ten ints
int (&arrRef)[10] = arr;  //  arrRef refers to an array of ten ints
int *(&arry)[10] = ptrs; // arry is a reference to an array of ten pointers

size_t

size_t is a machine-specific unsigned type that is guaranteed to be large enough to hold the size of any object in memory.

Lambda expression

auto Runtime Performance

Type deduction is done in compile time instead of runtime.2

Variable Number of Arguments

  • initializer_list<T>

    1
    2
    3
    4
    5
    6
    7
    
    void foo(initializer_list<int> il)
    {
    	for(auto x: il)
    		cout << il << " ";
    	return;
    }
    foo({1, 2, 3});
    

  • variadic template

  • ellipsis: no type check being conducted.

Interesting Stuff

Non-const Initialized Array

This is against the ISO standard. But, GCC allows this as an extension by default.

Pros: - convenient when initializing variable length arrays - Reduces memory fragmentation on heap.

Side effects: - Users may be able to overuse stack, causing runtime error.

Stopping Loops Before End

1
2
auto back = std::prev(STL.end());
for(auto it = STL.begin(); it != back; it = std::next(it));

Syntax Alias

  • Using A = B: A will be resolved as B at syntax level, similar to #define

Negative Division

Except for the obscure case where -m overflows, (-m)/n and m/(-n) are always equal to -(m/n), m%(-n) is equal to m%n, and (-m)%n is equal to -(m%n).

1
2
-21 % -8; /* -5 */    -21 / -8 /* 3 */
21 % 6; /* 3 */    21 / 6 /* 3 */