继承构造函数
class a { public: a(int i):m_i(i) {} a(double d, int i):m_d(d),m_i(i){} private: int m_i{0}; double m_d{0}; }; class b : public a { using a::a; // c++11 继承构造函数 int m_j{ 0 }; // c++11 成员变量初始化 }; int main() { b b1(356); b b2(2.0, 5); std::cout << "hello world!\n"; }
委派构造函数
class info { public: info() :type(1), name('a') { init(); } info(int i) :type(i), name('a') { init(); } info(char e) :type(1), name(e) { init(); } private: int type; char name; void init() { cout << "ok" << endl; }; }; class info2 { public: info2() :info2(1) {}; // 委派构造函数 info2(int i) :info2(i, 'a') {}; // 既是目标构造函数,又是委派构造函数 info2(char e) :info2(1, e) {}; private: int type; char name; info2(int i, char e) :type(i), name(e) { cout << "ok" << endl; } //目标构造函数 };
explicit operator 的应用
class convertable { public: explicit operator bool() const { return true; } }; void func(bool value) {} int main() { convertable c; if (c) cout << "ok" << endl; func(c); std::cout << "hello world!\n"; }
列表初始化
#include <initializer_list>
initialize_list<t>126
pod
平凡:构造、析构、虚函数
标准布局,非静态成员只能出现在一个类中,成员变量权限相同,第一个变量不能是基类类型,不含虚的
template<typename t> struct std::is_trivial;
template<typename t> struct std::is_standard_layout;
template<typename t> struct std::is_pod;
cout << std::is_pod<std::string>::value << endl;
is_same<t1, t2>::value
用户自定义字面量
inline namepace
sfinae
移动语义
左值,右值,右值引用
不能取地址,没有名字的,就是右值,包括将亡值&纯右值;
常量左值引用=万金油
常量右值引用没有应用价值,只有非常量右值引用。
#include <type_traits>
struct copyable
{
copyable() {}
copyable(const copyable& o) { cout << "copied" << endl; }
copyable& operator=(const copyable& o) { cout << "copied2" << endl; return this;}
copyable(copyable&& o) { cout << "moved" << endl; }
};
copyable returnrvalue() { return copyable(); }
copyable&& o = returnrvalue();
const copyable& p = returnrvalue();
cout << is_rvalue_reference< decltype(o) >::value << endl;
cout << is_rvalue_reference< decltype(p) >::value << endl;
cout << is_lvalue_reference< decltype(p) >::value << endl;
std::move
强制转化为右值
move_if_noexcept
is_move_constructible<unknowntype>::value
完美转发
template <typename t>
void perfectforward(t &&t)
{
func(forward<t>(t));
}
template<typename t, typename u>
void perdectforward(t &&t, u& func)
{
func(forward<t>(t));
}