一个构造函数调用同类另一构造函数,避免重复初始化代码。
class Person {
string info;
public:
Person() : Person(0, "") {}
Person(int age) : Person(age, "") {}
Person(int age, const string& name) {
info = name + " is " + to_string(age) + " years old.";
}
};
大括号初始化适用于所有类型,防止窄化转换。
int a{5};
vector v{1,2,3};
Person p{10, "Mike"};
int x = 5.3; // 隐式窄化
int y{5.3}; // 编译错误:防止窄化
强类型空指针,解决重载歧义。
void f(int); void f(char*); f(0); // 歧义 f(nullptr); // 明确调用 f(char*)
class Person {
int age = 10;
string name = "Mike";
};
class NonCopyable {
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
};
static_assert(sizeof(int)==4, "int must be 4 bytes");
vector> v; // C++11 合法
class Base { public: Base(int); };
class Derived : public Base {
using Base::Base; // 继承所有基类构造函数
int extra = 0;
};
void print(initializer_listil) { for (int x : il) cout << x << ' '; } print({1,2,3,4,5});
int a[100]; sort(begin(a), end(a)); // 统一容器与数组语法
class Base { virtual void f(); };
class Derived : public Base {
void f() override; // 必须重写基类虚函数
};
class FinalClass final {}; // 不可继承
templateusing Vec = vector ; Vec v;
union {
int i;
double d;
Person p; // C++11 允许含构造函数的类型
};
struct S { int x; };
sizeof(S::x); // C++11 允许无对象
int a[] = {-2,-1,0,1,2};
auto pos = [](int x){ return x>0; };
all_of(begin(a), end(a), pos); // false
any_of(begin(a), end(a), pos); // true
none_of(begin(a), end(a), pos); // false
copy_n(a, 5, b);
copy_if(begin(a), end(a), b, pos);
iota(begin(a), end(a), 10); // a[i] += 10
constexpr int fact(int n) { return n<=1?1:n*fact(n-1); }
int arr[fact(5)]; // 编译期计算 120
核心:T&& 万能引用 + std::forward 保持值类别。
templatevoid wrapper(F&& f, Args&&... args) { f(forward (args)...); // 完美转发参数 }
七种转发方案对比,唯有右值引用+修改推导规则(万能引用)实现完美转发:左值传左值,右值传右值,不修改 cv 限定,支持移动语义。