Knowledge of C + + problem collation

Source: Internet
Author: User

How to balance performance, choose C++stl container rationally?

ANSER:

The first thing to figure out is what the problem is, assuming the STL problem.

STLCan simply feel that is the algorithm + data structure, all the container algorithm selection and implementation are carefully designed and rigorous testing, a few mainstream STL implementation will not have a big problem.

performance problems usually come out of memory data operations, with three memory operations. Memory reads, memory replication, and memory allocations .

So the choice of the appropriate container is to minimize the memory operation, especially the copy operation, such as frequent middle insert delete do not choose Vector , frequent random visit do not choose list .

Except for the low-level error of choosing the wrong container, the performance bottleneck is basically the object inside the container. How to resolve:

    1. putting an object pointer inside a container instead of an instance, the object lifecycle is managed by itself , only when there is a real performance problem to consider, because the risk of memory leaks is quite high.
    2. Customizing allocator , Implementing an Object memory pool , is only used when confirming that the memory allocation is a bottleneck.
    3. Do not take two container instances to do assignment, the incoming parameters with pointers or references, the outgoing parameters swap to implement the container data transfer, it is important to confirm that they know what is doing.
Questions about C + + arrays and pointers?

when an array is taken from an address. The array name is not interpreted as its address . Wait a minute. is the array name not interpreted as the address of the group? Not at all: the array name is interpreted as the address of its first element , and the address operator (that is, &) is applied to the array name, resulting in the address of the entire array :

short tell[10];        //声明一个长度为20字节的数组(short型变量大小为2字节)cout << tell << endl;  //显示&tell[0]cout//显示整个数组的地址

Digitally, these two addresses are the same, but conceptually, &tell[0] (that is) the address of tell a 2-byte memory block, and the &tell address of a 20-byte memory block.

So. An expression adds tell+1 2 to the address value. The expression adds &tell+1 an address value of 20. Other words. tellis a pointer short ( short* ), and &tell is a pointer to an array that contains 10 elements short (short(*) [10]) .

You might ask, how did the &tell description of the type described above come about?
First, you can declare and initialize such pointers like this:

short (*pas) [10//pas指向一个有10个short元素的数组

Assuming that the parentheses are omitted, the precedence rule will be pas [10] combined first. Result pas is an short array of 10-type pointers. The parentheses are therefore indispensable.
Second, suppose to describe the type of narrative variable. The variable names in the declaration can be deleted. So. pasis of type short(*) [10] .
Other than that. Because it pas is set to tell . So *pas with the tell equivalent, so the (*pas) [0] tell first element of the array.

Back to the problem itself, when int the size of the type variable is 4 bytes, arr It is the address of a 4-byte memory block, and the &arr address of a 40-byte memory block.

Although the starting position of the two memory blocks is the same, the size is different.

The master can add these two lines to the code to control the output:

cout1 << endl;  //地址+4cout1//地址+40

Demo Sample code:

int  arr[10123456789 };    cout << &(arr[0]) << endl;    cout << arr << endl;    cout << &arr << endl;    cout1 << endl;    cout1 << endl;

Output:

0013FE600013FE600013FE600013FE640013FE88请按随意键继续. . .
What is the difference between 0 and NULL in C + +? With delete, with P=0, or with P=null good? Why?

ANSER:

First of all. Be clear. NULLis an untyped thing, and it's a macro. And this is the thing that C++ started from birth. Is the C++ father of the thing, he praised as far as possible to avoid macros . And in his FAQ , there is a corresponding interpretation of the NULL 0 . Also talked about this a little bit.

In the C++ standard. We can see a word called null pointer constant , in fact, C++11 before the standard. is simply to admit it 0 null pointer constant . So, in the C++ , we can often hear a saying that is given null pointer . Should be used 0 rather than NULL .

and nullptr pointer constant this word C++11 after the announcement, finally added a member, that is nullptr . And unlike NULL the essence, there are nullptr types (put in the stddef header file), type is, and it is typdef decltype(nullptr) nullptr_t because of the type, which gives us the compiler implementation nullptr of the time brought a lot of other details of the consideration, of course, also gives the user a lot of other protection, So let's assume your compiler supports it nullptr , so please be sure to use it nullptr !

nullptrthe appearance of the background, in fact, is very easy, C++ philosophically speaking, the C++ father has been null pointer not a formal expression of dissatisfaction. More project, however, is about overloading the problem.

void f(void*){}void f(int){}int main(){    f(0// what function will be called?}

and introduced the nullptr . This problem is really solved, it will be smoothly transferred to void f(void*) this version number.

All right. Really think that's it nullptr ? As I said before, nullptr there are types, called nullptr_t , which give us a lot of things to consider about compiler implementations. Unfortunately, let's give some examples of the wonderful flowers.

union U{    long i;    nullptr_t t;};int main(){    U u;    3;    printf("%ld\n",(long// What it is? 0 or 3?}

So is this supposed union to be semantic or nullptr semantic? This is not said in the standard, we have been arguing for a long time.

Of course, the implementation of our compiler is still nullptr the semantics, the result is 0 .

And nullptr there are types after that. What else can you do? That is, of course, the ability to catch exceptions.

int main(){  try  {    thrownullptr;    }  catch(nullptr_t)  {  } }

You throw a NULL try? See what he should take, it is because there is no type, so it is necessary to use its essential type. longfor example, something. You throw a 0 try? It is also not the so-called null pointer type, is to use what int to collect.

So, it makes nullptr sense to be respected, and we consider a nullptr lot of detail when the compiler implements it. There are a lot of situations that you might not be able to use all the time, and we're going to test it. The goal is to ensure the use of developers. Again that remark. Assuming your compiler supports it nullptr , be sure to use it nullptr !

Finally, a little bit more, 0 in a C++ very wonderful thing. For example, why pure virtual function is used =0 to set up, do not know that there is no classmate to consider the problem is not.

Assuming you understand philosophy profoundly C++ , this should be a very simple question to answer. Learn the language, you must learn its philosophy, you know the beauty of it. The power of it. Especially C++ .

How do I calculate the size of a struct with pointers? Problem:
struct X{    char a;    float b;    int c;    double d;    unsigned e;};

Because of the requirement of address alignment when storing variables, the size of this struct should be 32.

Let's say I define a random type of pointer

struct X{    char a;    float b;    int c;    double d;    unsigned e;    int *f;};

According to the address alignment requirements. Such a struct size should be 40, but it is still 32.

I'm going to add a random type of pointer

struct X{    char a;    float b;    int c;    double d;    unsigned e;        int *f;        double *g;};

As a result, the size of the structure becomes 40 directly. Assuming that the pointer size is address bus size, 2 pointers are 8 bytes, and the original 32 bytes are exactly equal to 40 bytes, and also meet the requirements for address alignment when storing variables.

But why just add a pointer to the same. The two have changed.

Reply:

At the beginning, it was this.

struct  X {char  A; //1 bytes  char  padding1[3 ]; //3 bytes  float  b; //4 bytes  int  C; //4 bytes  char  padding2[4 ]; //4 bytes  double  D; //8 bytes  unsigned  e; //4 bytes  char  padding3[4 ]; //4 bytes }; 

A pointer is added after this

struct  X {char  A;    //1 bytes    char  padding1[3 ];    //3 bytes         float  b;    //4 bytes           int  C;    //4 bytes    char  padding2[4 ];    //4 bytes        double  D;    //8 bytes      unsigned  e;    //4 bytes          int  *f; //4 bytes };  

And then one more pointer is this

structY ZCharA//1 bytes    Charpadding1[3];//3 bytes    floatb//4 bytes    intC//4 bytes    Charpadding2[4];//4 bytes    DoubleD//8 bytes    unsignedE//4 bytes    int*f;//4 bytes    Double*g;//4 bytes    Charpadding3[4];//4 bytes};

Is that understood more?

Wheel Brother's answer. Explains the principle

Let me add the answer to the anonymous user.

The first figure is this

struct  X {char  A; //1 bytes  char  padding1[3 ]; //3 bytes  float  b; //4 bytes  int  C; //4 bytes  char  padding2[4 ]; //4 bytes  double  D; //8 bytes  unsigned  e; //4 bytes  char  padding3[4 ]; //4 bytes }; 

padding1Existence is due to the offset(b) need to be align(b) divisible, so plug three char .

bThe offset byte is an integer multiple of its own byte, so a three-byte offset is added

padding2Existence is due to the offset(d) need to be align(d) divisible, so plug 4 char .

The reason is ditto

For all basic types, align(T)==sizeof(T) so there are two above.

align(X)How much is that? The biggest of all the members, of course align , is align(d)==8
Well, so it has to be sizeof(X) align(X) divisible padding3 .

The size of the entire structure must be divisible by align the largest of the trees.

Knowledge of C + + problem collation

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.