Skip to content

C++11 Programming

bellbind edited this page Oct 26, 2013 · 8 revisions

auto variable and numeric types

Almost all declared statement can use only auto name = ....

  • auto i = 0;: The type of i is signed int. Warning occurred when comparing to unsigned variables
    • auto i = 0u;: i as unsigned int

Anonymous function (lambda function) syntax

int outer1 = ...;
int outer2 = ...;
// capture outer1 as value and outer2 as reference
auto func = [outer, &outer2](int arg1, void* arg2) -> void {

};
// type of  func is "void (*func)(int, void*)"

It can use this type of function declaration at named functions. e.g.

auto func(int, void*) -> void;

auto func(int arg1, void* arg2) -> void {
}

using func_t = void (*)(int, void*);

int main()
{
  func_t f = func;
  f(0, nullptr);
  return 0;
}

But this type notation cannot be used at statements of variable and typedef. (using is available instead of function typedef)

4 type cast

  • const_cast<t>(v): remove const from const t v
  • dynamic_cast<t>(v): object down cast (runtime cast)
  • static_cast<t>(v): C down cast (compile time cast). when o = static_cast<t>(v), t o = v is valid in C.
    • from void* to other pointers, use static_cast
  • reinterpret_cast<t>(v): force cast as a memory fragment

inline function with const reference arguments

For non-pointer arguments in inline function, use type const T& instead of T to avoid call copy constructor.

e.g. from:

T obj1
char* obj2

//do something with obj1 and obj2
...

as

inline void func(const T& arg1, const char* arg2) {...}


T obj1
char* obj2

//do something with obj1 and obj2
func(obj1, obj2);