C/C ++ tips (1)

Source: Internet
Author: User

1. Internal implementation of vector

For vector, any insert/delete operation will invalidate the iterator, so be careful

The internal implementation of vector is actually a continuous memory, which is different from the traditional array. It can be resized without overstepping.

The vector iterator is the simplest pointer to the type in the container. There are three internal pointers: Start (pointing to the first address of the data storage area), finish (using the end Of the data area), end_of_storage (pointing to the end of the capacity, the capacity is generally surplus ). When the finish pointer is equal to the end_of_storage pointer, the capacity is fully loaded. If you continue to insert elements, you must expand the capacity.

When resizing is required, the space adapter searches for a larger memory space and points start to the first address of the new memory, copies the original data, inserts the new data, and updates finish and end_of_storage. Generally, the scale is twice the original capacity.

2. debug and release

Debug is usually called a debug version. It contains debugging information and does not optimize the Code to facilitate programmers to debug programs.

Release is called a release version. It usually optimizes the code so that the program is optimal in terms of code size and running speed, so that users can use it well.

Only debug programs can set breakpoints for one-step execution.

In fact, there are no boundaries between debug and release. They are just a set of compilation options, and the compiler only acts according to the predefined options. In fact, we can even modify these options, optimized debuggable version or released version with tracking statement.

3. Differences between references and pointers

In terms of concept, a pointer is essentially a variable that stores an address. It is logically independent and can be changed, this includes the changes to the addresses it points to and the changes to the data stored in the addresses it points.

A reference is an alias, Which is logically independent and has a dependency. Therefore, the reference must be initialized at the beginning, in addition, the referenced objects cannot be changed throughout the lifecycle.

In C ++, pointers and references are often used to pass function parameters. However, pointer passing parameters and reference passing parameters are essentially different.

A pointer passing parameter is essentially a value passing an address value. During the transfer process, the shape parameter of the called function is processed as the local variable of the called function, that is, the memory space is opened in the stack to store the value of the real parameter put in the main function, this forms a copy of the real parameter. The feature of value transfer is that the operations performed by the called function on the formal parameters are all performed as local variables, without affecting the values of the real parameters of the main function.

To sum up

Similarities are the concept of addresses.

The Pointer Points to a memory. Its content is the address of the memory, and the reference is the alias of a memory.

Differences:

1) the pointer is an entity and the reference is only an alias.

2) The reference can only be initialized once during definition. The reference is not variable after definition, and the pointer is variable.

3) The reference has no const, the pointer has const, And the pointer of const is immutable.

4) The reference cannot be null, And the pointer can be null.

5) sizeof (reference) gets the size of the variable to which it points, while sizeof pointer gets the size of the pointer itself.

6) The result of the auto-increment operation for pointer and reference is different.

7) references are type-safe, but pointers are not.

4. Replication Construction Mechanism

A copy constructor is a special constructor called by the compiler to construct and initialize Other Objects Based on the same class. The unique parameter (Object Reference) is an unchangeable (const) type.

Three methods of calling the copy constructor are provided.

1) An object is used as a parameter to pass in the function body as a value

2) an object as the return value of the function is returned from the function by passing the value.

3) one object is initialized to another object (often called replication initialization)

Summary: when an object is passed by value (whether as a function parameter or as a function return value), the compiler will first create a temporary copy of this object, when a temporary copy is created, the copy constructor is called.

If no copy constructor is explicitly declared in the class, the compiler automatically generates a default copy constructor, which completes the shortest copy between objects.

In some cases, the class member variables need to dynamically open up the memory. If the shortest is performed, the values in an object are completely copied to another object, such as a = B. If a member variable pointer in B has applied for memory, the member variable in a also points to that memory. This causes a problem: when B releases the memory, the pointer of A is a wild pointer and a running error occurs. In this case, we need to use the deep copy function to customize the copy constructor.

Deep copy and shallow copy can be simply understood as: If a class has resources, when the replication process occurs, if resources are re-allocated, this process is deep copy. On the contrary, if resources are not re-allocated, it is a small copy.

A copy constructor should be provided for classes that contain dynamically allocated members or pointer members.

While providing the copy constructor, you should also consider overloading the "=" value assignment operator symbol.

5. How is the virtual mechanism implemented?

The implementation mechanism of virtual functions in C ++ is to use virtual tables and virtual pointers. Each class defines a virtual table and each object defines a virtual pointer.

6. Role of virtual destructor

If a base class destructor is described as a virtual destructor, The destructor in its derived class is also a virtual destructor.

The purpose of the virtual destructor is to ensure that the Destructor is correctly executed when an object is deleted using the delete operator. After setting the destructor, you can use the dynamic join mode to select the destructor.

First, the subclass destructor is called, and then the subclass destructor is called to prevent incomplete destructor.

7. Differences between arrays and linked lists

In C ++, Arrays can be used to process data of the same data type, but the size of the array cannot be dynamically defined. That is, the size of the array must be determined before the array is used. In practice, sometimes the size of the array cannot be determined, and the array can only be defined as large enough. In this way, some space in the array may not be used, resulting in a waste of memory space.

A linked list is a common data distribution method, which is implemented by dynamically allocating memory. You can use new to allocate memory space when necessary. If you do not need it, use Delete to release the memory, which will not cause a waste of memory space.

The data in the array is continuously stored, while the linked list is randomly stored.

Random array access, low insertion and deletion efficiency. Accessing an element through the linked list needs to be traversed from the beginning, which is slower than the array, but you do not need to move the element when inserting or deleting the element.

8. process-oriented and object-oriented

Process-oriented is to analyze the steps required to solve the problem, and then use functions to implement these steps Step by step. You can call these steps one by one.

Object-oriented is to break down the problematic things into objects. The object is not created to complete a step, but to describe the actions of a things in the steps for solving the entire problem.

The difference between process-oriented and object-oriented is not as big as people think. Most of the object-oriented ideas can also be reflected in the process-oriented model. However, with the expansion of the system, the process-oriented model will not be able to cope with the biggest problem, resulting in system crash. The object-oriented approach is to solve this software crisis.

9. Virtual and pure virtual functions

1) virtual functions and pure virtual functions can be defined in the same class. Classes containing pure virtual functions are called abstract classes. Classes that only contain virtual functions cannot be called abstract classes.

2) virtual functions can be directly used or called in the form of polymorphism after being overloaded by the quilt class. Pure virtual functions must be implemented in sub-classes before they can be called, because pure virtual functions are declared only in the base class and are not defined.

3) both virtual and pure virtual functions can be overloaded in the subclass and called in a multi-state manner.

4) virtual and pure virtual functions usually exist in the abstract base class, and are overloaded by inherited sub-classes. The goal is to provide a unified interface.

5) virtual {method body}

Virtual {} = 0;

Virtual functions and pure virtual functions do not contain static identifiers. Static modified functions must be bound before compilation. However, virtual functions are dynamically bound, the lifecycles of functions modified by the two are also different.

6) If a class contains pure virtual functions, any statements that instantiate the class will be incorrectly generated. Abstract base classes cannot be called directly. After the quilt class inherits the overload, The subclass method must be called as required.

10. c ++ static global variables, static local variables, global variables, and local variables

By storage region: global variables, static global variables, and static local variables are stored in the global data area of the memory, and local variables are placed in the stack area of the memory.

By scope: global variables are valid throughout the project file; static global variables are valid only in the file that defines them; static local variables are valid only in the function that defines them, only the program allocates memory once. After the function returns, the variable does not disappear. The local variable is valid in the defined function and disappears after the function returns.

If the global variables and static variables are not manually initialized, the compiler initializes them to 0, and the local variables are unknown.

11. Common design modes

Single-piece mode, abstract factory mode and factory mode adapter mode decorative Mode Observer mode appearance Mode

Single-piece mode, which is the most widely used mode. Every formal software must use it for global configuration and unique resources.

In single-piece mode, the constructor should be set to protected to expand this constructor.

1) if a class occupies a large amount of system resources and these resources can be shared globally, it can be set to single-piece mode to force only one instance globally.

2) for a class, you need to count the instance. You can perform this operation in createinstanse and limit the number of instances.

3) For a class, you need to control the specific behavior of its instance. For example, you want the returned instance to be an instance of its own subclass. In this way, the client code can be transparent through the single-piece mode.

How to use the single-piece mode when multiple threads are used.

Ans: multithreading should also be a single piece, because the threads share the memory.

What should I do if the number of restricted instances cannot exceed 10?

Ans: use something similar to the thread pool

12. Graphics

Histogram equalization: changes the gray distribution of image pixels.

Airspace Filtering: Enhance spatial images

Linear sharpening filtering and non-linear smoothing filtering

13. Where are the function bodies stored in C ++?

The memory pattern of C ++ programs is usually 4 zones

1) Global Data zone: stores global variables, static variables, and constants.

2) code zone: stores the code of all class member functions and non-member functions (to know where the code zone is)

3) STACK: stores the local variables, function parameters, return types, and return addresses allocated for running the function.

4) Heap area: the remaining is the heap (using new and delete)

14. Benefits of using reference as the type of function return value and rules to be followed

Benefit: no copies of returned values are generated in the memory.

Note:

1) The local variable reference cannot be returned.

2) You cannot return a reference to the memory allocated by the new function. (because the reference knowledge returned by the function is used as a local variable, it is not assigned to an actual variable, the referenced space cannot be released, causing memory leakage)

3) can return the reference of class members, but it is best to set it to const

4) The function of declaring a stream operator to reference the returned value of an overload operation

Because operators are usually used consecutively, the pointer needs to create duplicate copies, which is not desirable. The only method is to use references.

15. How can I find errors when the program runs suddenly and crashes?

It seems that I didn't understand what the interviewer said, so I used a breakpoint to locate the wrong area line by line.

Later, he explained that he wanted to narrow down the scope of the error step by step based on the crash point, and said that this was an idea ..~~~ Then I began to draw circles... Most of the time we do this, but we can't say it.

16. Internal Implementation of Map

Vector encapsulates arrays, list encapsulates linked lists, and map and set encapsulate Binary Trees (completely unexpected ~~)

Further ask why map and set insertion and deletion are more efficient than other sequential containers

Because all the elements in map and set are stored as nodes, their structure is similar to that of linked list nodes. The reason for high efficiency is that you don't need to copy the memory or move the memory. You only need to modify the node pointer to point to it.

17. What are the basic graph transformations?

Zoom in, zoom out, rotate, stretch, viewpoint, transform, coordinate ing ......

After that, I asked a lot of questions about this ..~ Such as transformation matrix, 3D image rotation, and graphics algorithms

18. What is the role of extern C?

The main function of extern "C" is to call other C code correctly. After extern "C" is added, it indicates that the code of the compiler is compiled in C language instead of C ++. C ++ supports function overloading. Therefore, during function compilation, the parameter types of the function are added to the compiled code, not just the function name; C language does not support function overloading. Therefore, when compiling a function in C language code, the parameter type of the function is not included. Generally, the function name is included.
This function is very useful, because before the emergence of C ++, many codes were written in C language, and the underlying library was also written in C language, to better support the original C code and the written C language library, we need to support C as much as possible in C ++, and extern "C" is one of the strategies.

19. Let's talk about the role of # ifdef...

Prevent the header file from being repeatedly referenced.

20. What is the role of the keyword static?

Static global variables cannot be used by other files
Other files can define variables with the same name without conflict.
Static functions cannot be used by other files
Functions with the same name can be defined in other files without conflict.
We all know that the space allocated by the function on the stack will be released at the end of the function execution. If you want to save the value of the variable in the function to the next call, you can use static variables.

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.