Skip to content

C++ Syntax

迭代器 Iterator

谓词 Predicate

类型转换

  • static_cast
    • 编译时检查
    • 从基类到衍生类的转换 downcast
  • dynamic_cast<T>
    • 运行时检查
    • T 必须是类的指针或引用
    • T* nullptr 如果运行时类型不是 `T
  • const_cast
    • 用于移除或添加 const
  • reinterpret_cast

    • 改变数据类型的解释方式
  • c-style cast

虚函数

虚表,虚表指针

智能指针

标准库提供了三种智能指针类型

  • std::unique_ptr
    • owns the object it holds a pointer to
    • is not CopyConstructible, nor CopyAssignable; however, it's MoveConstructible and MoveAssignable
    • stores a pointer to an object and deletes that object using the associated deleter when it is itself destroyed
  • std::shared_ptr
  • std::weak_ptr
class widget {
private:
    std::unique_ptr<int[]> data;
public:
    widget(const int size) { data = std::make_unique<int[]>(size); }
};
unique_ptr<X> f() {
    unique_ptr<X> p(new X); // or {new X}
    // maybe throw an exception
    return p; // the ownership is transferred out of f()
}

constexpr

  • provides more general constant expresssions
  • allows constant expressions involving user-defined types
  • provides a way to guarantee that an initialization is done at copile time
enum Flags { good=0, fail=1, bad=2, eof=4 };
constexpr int operator|(Flags fl, Flags f2) { return Flags(int(f1)|int(f2)); }

constexpr int x1 = bad|eof;

struct Point {
    int x, y;
    constexpr Point(int xx, int yy): x(xx), y(yy) {}
}
constexpr Point origo(0, 0);

Lambdas

  • capture list
  • (optionally) its arguments and their types
  • the action to be performed as a block
  • (optionally) the return type
  • [=] 指定通过值捕获变量,lambda 表达式具有自己的值副本
  • [&] 表示通过引用捕获引用的所有变量
[=] () mutable throw() -> int
{
    int n = x + y;
    x = y;
    y = n;
    return n;
}
std::vector<int> v {1, 2, 3, 4, 5};
int x = 2;
int y = 4;
auto result = find_if(begin(v), end(v), [=](int i) { return i > x && i < y; });

Variadic Templates

template<class... Types>
tuple<Types...> make_tuple(Types&&... t) // `&&` indicates rvalue reference
{
    return tuple<Types...>(t...);
}
auto x = make_tuple("Hello", {1,2,3}, 1.2);

Rvalue references

define "move constructors" and "move assignments" to move rather than copy their argument

template<class T> class vector {
    vector(const vector&); // copy constructor
    vector(vector&&); // move constructor
    vector& operator=(const vector&); // copy assignment
    vector& operator=(vector&&); // move assignment
}

An rvalue reference can bind to an rvalue (but not to an lvalue)

X&& rr1 = f(); // fine: bind rr1 to temporary
X&& rr2 = a; // error: bind a is an lvalue

move(x) means to "treat x as an rvalue"

template<class T>
void swap(T& a, T& b)
{
    T tmp = move(a); // could invalidate a
    a = move(b); // could invalidate b
    b = move(tmp); // could invalidate tmp
}