C ++ knowledge points summary document

C ++ knowledge points summary document

  • Continually updated
  • Zhaohuaxishi. Do not write it down, as if everything would be all the testimony.
  • Programming comes from life, is nothing more than an abstraction of reality.
  • This document finishing when I found that he is nothing more than knowledge of C ++ is the tip of the iceberg
  • Another, C ++ 11 is really horrible , the new "feature" really a "terrorist predicament"
  • Another note: I Caishuxueqian, it is inevitable that errors and omissions, but also hope the wing

1. Basic Concepts


Memory Management

  • C ++ in memory division (content from blog ):
    • stack
      • By the user using new delete keyword management memory area
    • Stack
      • Stack used to store temporary variables, such as local variables in the function, automatically cleared when the code block
    • Free store
      • Block of memory allocated by malloc and so on, he and the heap is very similar, but it is free to end their lives
    • Global / static storage area
      • Global and static variables are assigned to the same piece of memory
    • Constant storage area
      • Special storage area inside the store they are constant (not quite understand, free to sweep under the blind)
  • new keywords
    • To open up a space in memory (heap), the user obtains a pointer to a memory location in the target pointer
    • Usage reference example

      //申请一块指向单个int对象的内存, 并将值初始化为"5"
      int *ptr_0 = new int(5);
      
      //申请一块指向5个连续int类型对象的内存
      //使用C++11统一的花括号初始化, 直观地对内存进行初始化
      int * ptr_1 = new int[5]{1,2,3,4,5};
      
  • delete the keyword
    • Delete the use of new application memory
    • Usage reference example

      //删除之前申请的内存
      delete ptr_0;
      //删除数组的写法, 注意
      delete [] ptr_1;x
      

Left and right value value

  • Lvalue
    • In general, the left value is variable (can be assigned), "to appear in the equal sign (an assignment) to the left of" values ​​are left
    • Can take the address with a name, is non-temporary lvalue
  • Rvalue
    • "Temporary values ​​appears to the right of the equal sign" has become the right value, C ++ will produce a temporary variable to store the results of the right value of the expression usually
    • Can not take the address, no name, the right value is temporary

Understand the essence, the creation and destruction of controlled behind the scenes by the compiler , programmers can only ensure effective at the line of code is the right value (including immediate);
and user-created, known by its survival scoping rules , is left value (including local variables and the function returns a reference to const objects).
Taken blog

  • Value the value of the left and right reference example

    int a{};
    //下式中a是左值, 5+1会产生一个临时变量6, 是右值
    a = 5+1;

Quote

  • Left reference value
    • Lvalue reference is a reference value to the left, similar to starting a variable alias
    • Often quoted
      • Use const reference value is modified when the left will become a constant reference
      • Often cited reference value left , the values can not be modified other than the referenced object, and the left common reference the same value
      • Often cited references rvalue (such as constant), it generates a temporary variable storage target
    • Left value cited reference example

      int var = 1;
      int &ref = var;   // 定义一个左值引用变量
      ref = 2;          // 通过左值引用修改引用内存的值
      
      //以下语句会报错, 10不是一个合法的左值
      //int &ref0 = 10;
      //用const修饰, 常引用, 引用常量
      const int &ref0 = 10;
      //等价于下面两行代码
      const int temp = 10; 
      const int &ref1 = temp;
      
  • Rvalue references
    • Rvalue reference for the new concepts introduced in C ++ 11
    • Presence rvalue reference is to reduce the construction and destruction of the operation target, so as to enhance the efficiency of
    • Compilation of the underlying case when the right to achieve the same value, use a temporary variable storage references cited constant target value, except that the rvalue reference modified reference value
    • Rvalue references reference example

      //右值引用
      int && rref = 10;
    • Rvalue reference practical application by reference

      There is a class definition

      class C  
      {
        public:
          //获得类C的一个实例
          static C getObject() { return C(); }
      };
      //这一行会调用类C的复制构造函数, 参数为getObject()函数产生的临时对象
      //其后临时对象会调用析构函数销毁
      C c = C::getObject();
      
      //右值引用避免了一次中间临时变量的构造与析构过程
      //引用直接指向函数返回时构造的对象
      C &&rref = C::getObject();
      
      Some tips
      1. When the content returned by the function in vitro function still exists when (usually the left value) can be considered return a reference to improve efficiency
      2. The content of the function can not be returned in vitro function continuing time (for example, local variables in the function body, or right value), may be used in an rvalue references return value to improve efficiency
  • Folding reference
    • First of all, C ++ in prohibited "cited references" that " Reference to Reference ", that is not allowed to quote (verb) a reference (noun)
    • When nesting a plurality of reference, using the following rules folding (collapsing) cited
      • All references folded rvalue rvalue reference value on the right is still a reference (A && && -> A &&)
      • All other references to the fold between the left types becomes a reference value (A & & became A &; A & && -> A &; A && & -> A &)
      • Left reference value is a reference value appears to the left of the collapsed reference nesting
      • Full references cited references rvalue rvalue is collapsed nesting

lambda expressions

  • lambda expressions in C ++ 11 is the introduction of new content
  • lambda expressions are used to define and use anonymous functions , you can simplify part programming, but mainly used to improve readability, make the program more concise
  • Lambda expression syntax

    [捕获列表] (参数列表) 修饰信息 -> 返回值类型 {函数体}
    
    [capture list] (params list) mutable exception-> return-type {function-body}
    • Capture list
      • It can not be omitted , capture list marks the beginning of a lambda expression
      • If the capture field is [], the lambda expression can not access any external variables
      • The field may write "&" or "=" sign to control access mode
        • & Means access by reference
        • = Indicates visit by value
    • parameter list
      • asdf
    • Information modification
      • the mutable (optional): Indicates whether a lambda expression can modify variables captured
      • Exception (optional):
    • Return Type
      • Can be omitted
      • When the return type is omitted, the compiler automatically derived type
    • Function body
      • Anonymous function to execute statement

Object-Oriented

  • class keyword
    • class keyword to declare a class
  • Access control
    • Three access control
      • public
        • The public. All locations are accessible (including member functions, member functions of the derived class, non-member functions of this class or derived class friend)
      • protected
        • Protection only member functions, member functions of the derived class, the derived class's friend, the kind of friend you can visit
      • private
        • Private Only member functions of this class can be accessed friend
    • Tomomoto
      • Friend program provides a mechanism that allows ordinary function can access the class member functions can access all content
      • Access to the same friend and member functions namely: content can be accessed by member functions, can also be accessed friend
      • Need to note that, in this case the "member functions" and "friend function" refers to the same class member functions and friend functions
        • For example, a friend of the derived class can not access the private members of the base class, because members of the derived class can not access private members of the base class
    • Access Control Examples

      class C
      {
        friend void fun0(C& c);//友元函数声明
      public:
        int pub;//公有成员
      protected:
        int pro;//保护成员
      private:
        int pri;//私有成员
      };
      
      void fun0(C& c)
      {
        c.pub;
        c.pro;
        c.pri;//没问题, 可以访问
      }
      
      class C_plus:public C//公有继承, 基类成员可见性不变
      {
        friend void fun2(C_plus &c);//友元函数声明
      
        void fun1()
        {
          this->pub;
          this->pro;
          //this->pri;//报错, 不可访问
        }
      };
      
      void fun2(C_plus& c)
      {
        c.pub;
        c.pro;
        //c.pri;//报错, 不可访问
      }
  • Default member function (if not manually, the compiler will automatically)
    • Constructor
      • When the function when a new object generated by calling
      • Constructors have no return value , you do not need to specify the void
      • A typical implementation

        //"C"为类名
        C();//一个无参构造函数
        {
          //do something
        }
        C(int a, int b)//一个接受两个int值的构造函数
        {
          //do something
        }
    • Destructor
      • When the object is a function of die (destruction) when called
      • A typical implementation

        //"C"为类名
        ~C()
        {
          //do something
          //通常情况下这里会有一些代码用来delete在构造函数中new出的内存指针
        }
    • Copy constructor (copy constructor)
      • Function when using an existing object creation (initialize) a new object when called
      • Only one reference copy constructor class object as a parameter of this (if not using the reference lead to infinite recursion)
      • The copy constructor's behavior related to the depth of the replication problem
        • Shallow copy : no matter what type of member variable, only the value of the member variable copy
        • Deep-copy : If the member variable is a pointer , it is generally not simply copy the value of the pointer, but should apply for a new memory block, and assign the new pointer type member variable pointer obtained
      • A typical implementation

        //"C"为类名
        C(const C & another)//必须使用引用作为参数; const可加可不加, 但建议加上
        {
          //do something
        }
    • Move constructor (C ++ 11)
      • When the object is a function of the content of existing objects transferred to a newly generated call (generally the original object should be invalid)
      • Transfer constructor for the member variable pointer type is usually taken shallow copy pointer members, and will be transferred to the object nullptr
      • A typical implementation

        //"C"为类名
        C(C && another)
        {
          //do something
        }
    • Mutator (assignment operator overloading)
      • Function when using an existing object has been assigned to another object called
      • A typical implementation

        //"C"为类名
        C& operator=(const C &another)
        {
          //do something
          return * this;
        }
    • Transfer function assignment (assignment operator overloading) (C ++ 11)
      • When the contents of an existing object is transferred to the function call when the other existing objects (generally the original object should be invalid)
    • Address-operator overloading
      • Fetch address operation for the object, generally do not need to achieve self-
      • A typical implementation

        //"C"为类名
        C* operator&()
        {
            return this;//直接将地址返回
        }
    • const fetch address operator overloading
      • Const object address for fetch operation, generally do not need to achieve self-
      • A typical implementation

        //"C"为类名
        const C* operator&() const
        {
            return this;//直接将地址返回
        }
  • Type conversion constructor
    • Type conversion for a constructor of the object is converted into another type of a class object
    • When a class object is required, but provides other types of objects can be converted to a class object automatically call the corresponding constructor function to convert the type of conversion
    • A typical implementation

      class C
      {
      public:
        int data;//成员变量
        //类型转换构造函数, 将int类型的值转换为类对象
        /*explicit */C(const int &_data)
        {
          this->data = _data;
        }
      }
    • explicit keywords
      • Sometimes, there is only a constructor argument , or a presence , although there is more than one argument, but in addition to the first argument the other parameters have a default constructor values , but do not want to be a type conversion constructor, you can use explicit keyword modified, it indicates that the constructor is not implicit, not automatically implicit call (Note: in addition to the above modification constructor function with explicit keywords does not make sense).
  • Type Conversion Functions

    In C ++, the name is also a type of operator, i.e. cast operator

    • Mainly used for implicit conversion, when a certain type of object is required, but provides a class object, automatically calls the corresponding type conversion function to convert
    • A typical implementation

      class C
      {
      private:
        int data;
      public:
        //转换函数(转换为int类型), 在需求int类型时传递C类的对象会自动调用
        operator int(){ return data; }
      }
  • Add at the end of const member function declaration
    • The list of parameters for the operating member function parameters implied in this add const pointer modification
    • That is: not allowed to modify the object this pointer; not allowed to call the object's non-const member functions

      //类成员函数
      void fun()const
      {
        //do something
      }
      
      //注:并没有下面这种写法, 只是本质上等价于下面的代码
      
      //"C"为类名
      //注意这里const是修饰类型C的
      //这意味着this指针指向的内容被看作常量
      void fun(const C * this)
      {
        //do something
      }
  • inherit
    • Inheritance represents a relationship of "is-A". That is, a derived class (special) base class.
    • Derived class (subclass) inherits all the members of the base class (parent class) of
    • Three kinds of inheritance
      • public ( visibility up , visible both inside and outside)
        • Public inheritance , members of the base class in a derived class remains unchanged (maintaining visibility declared in the base class) ( "member" includes member variables and member functions, also known as fields and methods)
      • protected
        • Protected inheritance , members of the base class, the visibility of the above protested, becomes protested in a derived class
      • Private ( lowest visibility , external invisible, not visible to the derived class)
        • Private inheritance , members of the base class in a derived class visibility becomes private
    • In short, high visible than the inheritance of resistance members in a derived class visibility is reduced as the inheritance of visibility
    • Overloaded member function, rewrite, hidden (these points is very important, is the C ++ object-oriented inheritance core)
      • overload (overloading)
      • the override (override / coverage)
      • Redefining (redefined / Hide)
    • Multiple Inheritance
      • Multiple inheritance too much trouble, to be honest did not really written the code, it is difficult to ensure thorough understanding. Skip

Polymorphism

  • Polymorphism refers to various forms of a thing
    • Static polymorphism, compile time
      • Function overloading
        • By contrast function call with a different function prototype version of the function call to infer specific
      • Generics
        • Different objects to achieve a unified interface (the interface here refers to the same set of operational programs) use the same set of templates, improved code reuse (duck typing)
    • Dynamic polymorphism
      • Object-oriented polymorphism
    • This section refers to the object-oriented multi-state
  • virtual keyword
    • Use the keyword modified virtual member function is called "virtual function"

Generics

  • By using C ++ templates to support generic programming mechanism
  • There are two types of templates
    • Function template
    • Class Template
  • Function template
    • Continued unfinished

move semantics


Exception Handling


2. Important keywords or operator

decltype

  • decltype is a keyword for the type of an object is captured
  • Value for the left and right values ​​have different performance
    • If decltype target type is (presumed to be) left value , the result is a reference type
    • If the target type is decltype (be inferred to) the right values , the result is not a reference type
  • Introduced by the C ++ 11

typeid

  • typeid is an operator that returns an object type information object
  • Generating a use after the typeid the type_info object type (C ++ the only way to create an object)
  • When the operand is typeid operator with no virtual functions when class type, typeid operator will indicate declared operand type , rather than the underlying object type
    • Personal understanding is: if you declare the class type of the operand does not have any virtual function, then call all the member functions of the operands will use to achieve its declared type version, then return to its underlying specific types would not make sense
  • When there is no virtual function needs to be set, for the purpose may be to virtual destructor. In fact, the presence of a base class destructor derived class virtual must be set , because it may not call the derived class destructor resources can not be completely released
//示例1
int a{};
//下面这一行语句的输出是"int"
cout << typeid(a).name();

There is a class definition

class C0
{ };

class C0_plus:public C0   
{ };

class C1
{
protected:
  //虚函数
  virtual ~C1() { }
};

class C1_plus :public C1
{
  virtual ~C1_plus() { }
};
//示例2

C0* p0 = new C0();
//下面的语句输出"class C0"
cout << typeid(*p0).name() << endl;

C0* p1 = new C0_plus();
//下面的语句输出"class C0"
cout << typeid(*p1).name() << endl;

//---------------------

C1* p3 = new C1();
//下面的语句输出"class C1"
cout << typeid(*p3).name() << endl;

C1* p4 = new C1_plus();
//下面的语句输出"class C1_plus"
cout << typeid(*p4).name() << endl;

auto

  • As early as the auto keyword already exists in the C ++ 98. it was used to indicate a variable automatic life cycle, but a local variable always has a default automatic life cycle, so auto rarely used, and at the time was superfluous of
  • C ++ 11 standard removed the traditional use auto keyword. Now, auto key for automatic type inference

    Digression
    is obvious, type inference auto execution is done at compile time, will not have any impact on operational efficiency .
    At the same time, C ++ compiler at compile time itself also needs to determine the type declaration and actual type of match, so it should not affect compilation speed (even if this affects not bad, pull away)

  • After the C ++ 14, the parameter capture lambda expressions can also use auto
  • Type inference can be used for auto template, the template will be omitted for the parameter type template derived type declaration in the parameter list
    according to the present embodiment taken from blog

    //传统写法, 需要专门为makeObject()的返回值类型在模板的参数列表中添加一项
    template <typename Product, typename Creator>
    void processProduct(const Creator& creator) {  
      Product* val = creator.makeObject();
      // do somthing with val
    }
    
    //使用auto的写法, 得到一定简化
    template <typename Creator>
    void processProduct(const Creator& creator) {
      auto val = creator.makeObject();
      // do somthing with val
    } 

const

class

typename

explicit

delete

using

  • Conventionally using keyword for introducing all or part of the namespace
    , such as:

    using namespace std;//导入std命名空间中的所有内容
    
    using std::cout;//只导入命名空间std中的cout
  • However, in the new C ++, the using typedef may be used instead
    , although the same function, but (if) to be more intuitive

    //这一条语句为std::string取了一个别名"stdstring"
    using stdstring = std::string;

    It can be used in the class declaration

    class C
    {
    public:
      using uss = std::string;
      typedef std::string tss;
    };
  • Also features a simplified statement of what the parent class member functions, not very understanding, time to write

mutable

  • For labmda expressions, lambda expressions indicating the variables may be modified to capture

exception

3. source code analysis

4. Some of the terms

  • RTTI
    • Run-Time Type Identification: Run-time type checking

Guess you like

Origin www.cnblogs.com/Sirius-Z/p/12239485.html