C ++ summary (c)

A, C ++ dynamic memory management:

1, C / C ++ runtime: memory distribution of
Here Insert Picture Description
a, known as the stack Stack, non-static local variables / function parameters / return values, etc., down the stack is increased.
B, segments are efficient memory mapping I / O mapping mode for loading a dynamic shared memory bank. The user can use the system to create a shared interface to shared memory, do inter-process communication. (Linux course if you do not learn this, and now only need to look at)
c ,. heap for dynamic memory allocation when the program is running, the heap is growing.
d, data segment - storing global data and static data.
e, snippet - executable code / read-only constants.
2, the difference between the malloc / calloc / realloc three functions
all three were allocated memory, stdlib.h library is a function, but there are some differences.
(1) malloc function. Which Prototype void * malloc (unsigned int num_bytes) ;
space num_byte as to apply, we need manually to calculate, as int * P = (int ) the malloc (20 is the sizeof (int)), if the compiler default int 4 bytes of storage, then the calculation result is 80 bytes, 80 bytes first application of a continuous space, the base address space and cast to type int, assigned to the pointer p, the application memory value at this time is uncertain.
(2) calloc function prototype void * calloc (size_t n, size_t size);
Which is a multi-parameter than the malloc function, does not need to calculate the size of space artificially, for example if he wants to type int application space 20, will int * p = (int *) calloc (20, sizeof (int)), so that It eliminates the hassle of man-made space calculation. But this is not the most important differences between them, the value of the malloc application space is random and not initialized, while calloc but after the application of space initialize one by one, and set the value to 0;
(3) realloc two essentially different functions above, the prototype void realloc (void * ptr, size_t new_Size)
is used for expansion of the dynamic memory (dynamic space and has not used the application, the space required expansion operation), PTR to point to the original space pointer base address, new_size capacity expansion for the next required size.

3, the difference between malloc / free and new / delete the

  • Common: both from the application heap space, and require the user to manually released.
  • The difference is:
  1. It is functions malloc and free, new and delete operators are
  2. Application of space malloc does not initialize, new can initialize
  3. When malloc space applications, manual calculations and transfer space, the new new type just subsequent to keep space
  4. malloc returns a value of void *, transfer must be strong in use, it does not require new, since the new type of heel is space
  5. When the application space malloc fails, the return is NULL, they must use judgment when empty, does not require new, but new needs to catch exceptions
  6. Apply custom type object, malloc / free only to open up space, does not call constructors and destructors, and new space will be called upon to apply the constructor to initialize the object is completed, delete the space before the release will call the destructor cleanup complete space resources

4, new / delete sum new [] / delete []

T new new:
1, * operator new new call void (size_t size)
{
malloc cycle applications ----> application is successful, the direct return
application failed - insufficient space to provide countermeasures (user)
provides: cycle application
does not provide: Throws
}
2, call the T constructor to complete the initialization control

Delete:
. 1, T destructor call resource release objects
2, void operator delete () to free space objects

new new T [N]:
. 1, space applications: void * operator new new [] (size_t size) -> void * operator
new new (size_t size) -> cycle using malloc application
2, the configuration of N objects: invoking the N constructor initializes the object

Delete []
. 1, the release of the N object resources: calling N times the destructor
2, releasing the space of N objects: void operator delete [] (void * p) -> void operator delete (void * p) -> free

Positioning new expression : space existing initialized new§ T (parameter):
1, * operator new call void (size_t size, void * WHERE)
{
return WHERE; the application does not require a real space, the space directly returns
}
2 , call the constructor of type T

Second, the template

1. What is a template? What is a generic programming?
Template : that is, the compiler generates code in the mold. Template is divided into function templates and class templates.
Generic Programming : writing generic code regardless of the type, is a means of code reuse. Template is the basis of generic programming.
2, function template instantiation

a> implicitly instantiates

If the compiler detects that the user of the function template is instantiated:
1, to find in the project - whether there is a specific type of treatment Add function
to find: a direct call, do not need to generate a template
not found: a further 2
2 looking in the project - whether Add the presence of template function of the type
found:
a, deduction argument type
B, template binding, the specific type of function generating process
C, the process invokes the generate specific types of functions
not found: compilation failed

Note : In the example of the template during the implicit, not implicit type conversion

b> shows an example of

If it is explicitly instantiate, corresponding to the template type has clearly embodying T, the compiler does not need to be the parameter type inference, generated directly according to <> type codes.
Note: If the argument type <> when the types do not match, the compiler may be implicit type conversion
successful transformation: generating code, compile
conversion fail: error

3, class template specialization

1> The concept : that of the template type parameter, then special treatment (most likely case template can be processed normally, but for some type of treatment is probably a mistake)

2> specialized classification

  • Full specialization : the template parameter list of all types of concrete
template<class T1, class T2>
class Data
{
public:
Data() {cout<<"Data<T1, T2>" <<endl;}
private:
T1 _d1;
T2 _d2;
};

template<>
class Data<int, char>
{
public:
Data() {cout<<"Data<int, char>" <<endl;}
private:
T1 _d1;
T2 _d2;
};
  • Specializations :
    1. partially specialized: template parameter list of some of the parameters specific
template<class T1, class T2>
class Data
{
public:
Data() {cout<<"Data<T1, T2>" <<endl;}
private:
T1 _d1;
T2 _d2;
};

// 将第二个参数特化为int
template <class T1>
class Data<T1, int>
{
public:
Data() {cout<<"Data<T1, int>" <<endl;}
private:
T1 _d1;
int _d2;
};

2. Let restrictions on the type template parameter list more stringent

//两个参数偏特化为指针类型
template <typename T1, typename T2>
class Data <T1*, T2*>
{
public:
Data() {cout<<"Data<T1*, T2*>" <<endl;}
private:
T1 _d1;
T2 _d2;
}

The type of extraction - implementation of the
principle: that the class template specialization of an application is only a means to increase the operating efficiency of the code
6. separate compilation
1> what it feels separate compilation?
A project, there may be multiple sources file, every source file is compiled separately, header files is not involved in compiling (exhibition Jian already in the preprocessing stage)
2> to finish the program to run properly, you need to go through those phases: pre-compiler, assembler, linker
Here Insert Picture Description

  • Preprocessing (Preprocessing These)
    . 1, macro substitution
    2, the header containing
    3, conditional compilation selection
  • Compiling (Compilation)
    pretreated finished file lexical analysis, syntax analysis, the semantic analysis and optimization, to form the corresponding assembly code .s.
  • Assembler (Assemble)
    the compiled machine code is translated into the assembler code, and generates .o relocatable object file of the target program.
  • Links (Linking)
    by the linker ld to link together object files and library files, and finally generate an executable file (executable file).

7, the advantages and disadvantages of the template

  • advantage

    1, the template code reuse, save resources, faster iterative development, C ++ Standard Template Library (STL) and therefore produce
    2, enhances the flexibility of the code

  • defect

  1. Template code bloat can cause problems, can lead to longer compile time
  2. Template compilation error, an error message is very messy and difficult to locate the error

Third, OJ line input and output

Output: To look at the subject carefully output requirements
Input: OJ algorithm: IO type and interface type OJ OJ
Interface Type OJ: interfaces with the algorithm has been available, only direct to encode
IO type of OJ: require the user to accept the test cases - some to enter the circulation
in two ways:
case 1: three shape the input: while (cin >> a >> b >> c) {...}
case 2: the entire input line: a plurality of word line, to find the longest length word while (getline (cin, s) )

Fourth, inheritance

1. Concept

  • Inheritance can improve code reuse
  • Expand while maintaining the original characteristics of the class
  • Reflecting a hierarchy

2. inherit permissions
public, protected, private
Here Insert Picture Description
three different inheritance: members of different access rights of a base class in a subclass of access or visibility
default inherited permissions: class-private struct-> public

3. ---- assignment rule must be compatible with public inheritance
If the inheritance is public - a base class and subclass is-a can be seen as an object a subclass of the base class,
use: when the external class, all the position of use of the base class can be a subclass object used to place

a, can be directly assigned to a group derived object class object, not vice versa
B, allowing the pointer or reference to the base class objects to sub-class, and vice versa, but can force conversion type (Problem: There may be security issues)

4. scope inherit
subclasses belonging to different base classes and scope. Whatever the inheritance, the base class private in a subclass members are not visible
with the same name hidden : there may be members of the same name in the base class and the derived class when the subclass object to access members of the same name, priority access to a derived class of their own

Hidden namesake :
member variables: the same as long as the base and derived class member variable names are the same irrespective of the type of
the member function: as long as the same name as the base class and the derived class member functions, is the same irrespective of the function prototypes

  • Note: The derived class test (), test (int), the two functions are not function overloading, reason: the scope is not the same
  • A derived class can not directly access members of the base class with the same name, If you insist on access, B :: test (); use is not very convenient or might forget to add B ::, resulting in some errors
  • Not recommended: An exception occurred in the same name as a member base and derived classes: Polymorphism

5. inheritance hierarchy: the rules of construction

  • 1> if the base class does not define a constructor, whether derived class constructor can
  • 2> if the base class constructor is a default constructor (the constructor with no arguments || with full default constructor), the derived class's constructor release can be provided
    at this time: the compiler is a derived class generates a default constructor (no arguments), and explicitly called base class constructor in a derived class constructor initializes a list of members of the base part has completed initialization
  • 3>. If the base class has a non-default constructor (the constructor with parameters), this time explicitly derived class must provide its own constructor, and must explicitly call the base class constructor initializes its position in the list constructor.
class B
{
      public: B(int a){}
};


//没有显式定义构造函数,一定编译出错
class D:public B{};
//原因
//1.如果一个类没有显式定义自己的构造函数,编译器将会生成一个默认的无参构造函数
//2.编译器必须要在派生类构造函数初始化列表显式调用基类的构造函数---问题:基类的构造函数具有参数,派生列在调用时必须要传参,但是编译器不知道应该传递什么参数而导致无法调用而引起编译失败


class D:public B
{
public D(int){} // 没有显式调用基类的构造函数
}//在基类中无法找到无参的构造函数而引起编译失败


//正确写法:
class D : public B
{
   public: D(int b): B(b){}
}
  • 4> inheritance hierarchy: when a derived object constructors and destructors - constructor and destructor order
    function call order : C () -> initialization list where the call A (), and execution completes -> execution derived class constructor function body ()
    Print : print go A () ----> C print ()
class A
{
   public:
       A(){}
       ~A(){}
};

class C:public A
{
    public:
       C():A(){}
       ~C(){}
};

void TestFunc()
{
    C d;
   //创建那个类的对象,编译器就会调用那个类的构造函数  
   //析构那个类的对象,编译器就会调用那个类的析构函数
}
Published 22 original articles · won praise 13 · views 1269

Guess you like

Origin blog.csdn.net/An_Mo/article/details/104286630
Recommended