C + +: The difference between some common knowledge points (collation)

Source: Internet
Author: User

The difference between struct and class
    • The difference between struct and class in C: struct is only a struct defined by a complex data type, and cannot be used for object-oriented programming; C language has no class keyword.
    • The difference between struct and class in the C + + language: For member access and inheritance, class default is private,struct default is Public;class can be used to represent template type, struct not; The use of inheritance often uses class, which is used to inherit the struct.
The difference between memory leaks and memory overflows
    • Memory overflow: Refers to the program when requesting memory, there is not enough memory space for its use, appear out of the memory, for example, the application of an int type of address space, but it is stored in a long type of data, it will result in a ram overflow.
    • Memory leak: Refers to the program after the application of memory, unable to free the requested memory space, memory leaks will cause the free memory space to become smaller, further causing memory overflow.
The difference between heaps and stacks
    • Management: The heap resources are controlled by the programmer (through Malloc/free, New/delete, easy to generate memory leak), the stack resources are automatically managed by the compiler.
    • System response: For the heap, the system has a list of idle memory address, when the system receives a program request, traverse the list, looking for the first heap of space larger than the requested space, delete the node in the list of idle nodes, The node space is allocated to the program (most systems record the size of this allocation at the first address of the memory space, so that delete can properly free up the memory space, and the system will re-place the extra parts into the idle list). For the stack, as long as the remaining space of the stack is larger than the requested space, the system will allocate memory for the program, or the exception of the stack space overflow error.
    • Space size: The heap is a discontinuous area of memory (because the system uses a linked list to store free memory addresses, which is not contiguous), the size of the heap is limited by the effective virtual memory in the computer system (32-bit machine is theoretically 4G in size), so the heap space is more flexible and larger. Stack is a contiguous area of memory, the size of the operating system is scheduled, Windows stack size is 2M (there is 1M, at compile time, VC can be set).
    • Fragmentation problem: For heaps, frequent new/delete can result in large amounts of memory fragmentation and reduced program efficiency. For stacks, it is an advanced post-out (FIRST-IN-LAST-OUT) structure that corresponds to and from one by one and does not produce fragmentation.
    • Growth direction: Heap up, increase to high address direction, stack down, to low address direction.
    • Allocation method: The heap is dynamically allocated (no statically allocated heap). Stacks have static allocations and dynamic allocations, static allocations are done by compilers (such as function local variables), and dynamic allocations are allocated by the ALLOCA function, but the dynamically allocated resources of the stack are automatically freed by the compiler without the programmer's implementation.
    • Allocation efficiency: The heap is provided by the C + + function library and the mechanism is complex, so the heap is much less efficient than the stack. The stack is the data structure provided by the machine system, the computer supports the stack at the bottom, allocates the special register storage stack address, provides the stack operation specialized instruction.
The difference between a pointer and a reference
    • Pointer is an entity, has allocated memory space, reference is just an alias, does not allocate memory space
    • Pointers are not required but preferably initialized, references must be initialized
    • A reference can be initialized only once, and the pointer may be assigned multiple times
    • There can be const pointers, but there are no const references, such as int* const P legal,int& Const p Some compilers will error, some compilers will warn and ignore the const modifier
    • Pointers can point to null values, references cannot point to null values
    • "sizeof Reference" gets the size of the variable object, and the "sizeof pointer" gets the size of the pointer itself.
    • Pointers and reference self-increment operators have different meanings
    • Pointers can have multiple levels, and references can only be one level
Five areas of memory allocation
    • The area of memory occupied by a program compiled by C + + is generally divided into the following 5 sections:
      • Stack: The compiler automatically allocates and frees the parameters, local variables, etc. that are used to store functions. It operates in a manner similar to a stack in a data structure.
      • Heap: Typically assigned and freed by programmers (via Malloc/free, New/delete), if the programmer is not released, the program ends up being recycled by the operating system. It is different from the heap in the data structure and is distributed in a similar way to a linked list.
      • Global/static zones: The storage of global variables and static variables is placed in a block, initialized global variables and initialized static variables in an area, uninitialized global variables and uninitialized static variables in another adjacent area, after the end of the program is recycled by the operating system.
      • Literal constant Area: store constant value, normal string, etc., do not allow modification, after the end of the program is recycled by the operating system.
      • Program code area: binary code that holds the body of the function.
    • Examples are as follows:
#include <stdlib.h>#include <string.h>int a = 0; // 全局初始化区char* p1;  // 全局未初始化区int main() { int a;            // 栈区 char s[] = "abc"; // 栈区 char* p2;         // 栈区 char* p3 = "123456";    // 123456\0在常量区,p3在栈区 static int c = 0;      // 全局/静态初始化区 p1 = (char*) malloc(10); p2 = (char*) malloc(20); // 分配得来的10和20字节在堆区 strcpy(p1, "123456"); // 123456\0放在常量区,编译器可能将它与p3所指向的"123456"优化成一个地方 return 0;}
The difference between new and malloc
  • Property
    • New/delete is an operator, a C + + keyword that requires compiler support; Malloc/free is a library function that requires header file support.
  • Parameters
    • The use of the new operator to dynamically allocate memory does not require a memory block size, the compiler calculates itself according to the type, and malloc allocates memory to explicitly indicate the required memory block size.
  • return type
    • The new operator allocates a pointer to the appropriate object type when the memory allocation succeeds, does not require coercion of type conversions, conforms to type safety, throws a Bac_alloc exception when allocation fails, and malloc allocates memory successfully returns a pointer of type void*, which needs to be cast to the desired type by forcing the type. Null value returned when allocation failed.
  • Non-Internal data Objects
    • New will call the operator new function, request enough memory, invoke the constructor of the type, initialize the member variable, and finally return a pointer to the custom type; Delete invokes the destructor and then calls the operator delete function to free the memory; malloc/ Free is a library function that can only dynamically request memory and release memory, and cannot complete the work of constructors and destructors.
  • Overload
    • C + + allows overloading of new/delete (which is actually overloaded operator new and operator delete), and, in particular, layout new (placement new) does not need to allocate memory for an object, but instead uses the specified address as the starting area of the memory. New completes the object's constructor call on this memory and initializes the memory segment and returns the memory address; Malloc/free does not allow overloading.
  • Memory Area
    • The new operator dynamically allocates space for an object from the free storage area, and the malloc function allocates memory dynamically from the heap. Free storage is an abstract concept of C + + based on the new operator, which is a free storage area where memory is requested by the new operator, and the heap is the corresponding area of memory allocated in the operating system. The free store is not equal to the heap, and the layout new can not be in the heap. A heap is an actual area, and a free storage area is a higher-level concept. Normally new is actually applying memory on the heap, but programmers can reload the new operator themselves, use other memory for free storage (uncommon), and C++primer Plus, the layout new that is mentioned in the book, can allocate memory on the stack for objects. In general, free storage is the concept of the interval for new applications.
3 relationship between species and differences inheritance (inheritance)
    • Represents Is-a, as shown in the following code:
class A {private:    int a;};class B : public A {private:    int b;};
    • Construction and destruction under the relation of inheritance
      = = constructed from inside Out = =
      The derived constructor first calls the base's default constructor before performing its own function. For example, Derived::D erived (...): ==base () = = {...};
      = = destruction from outside and inside = =
      The destructor for derived first executes itself before the destructor of base is called. For example, derived::~derived (...) {... ==~base () = =};
Composition (composite)
    • Represents Has-a, as shown in the following code:
class A {private:    int a;};class B {private:    A a;    int b;};
    • Construction and destruction under compound relation
      = = constructed from inside Out = =
      The constructor of B first invokes the default constructor of a and then executes itself. For example, B::b (...): ==a () = = {...};
      = = destruction from outside and inside = =
      The destructor of B first executes itself before the destructor of a is called. For example, B::~b (...) {... ==~a () = =};
Delegation (commissioned)
    • Composition by reference, as shown in the following code:
class A {private:    int a;};class B {private:    A* a;    int b;};

C + +: The difference between some common knowledge points (collation)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.