深入理解C++11 C3
继承构造函数
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));
}
浙公网安备 33010602011771号