Some programming tips and details for C + +

Source: Internet
Author: User
Tags shallow copy

1, sometimes, the function of many parameters, it is best to also line , such as:

CreateProcess (
Null
Cmdbuf,
Null
Null
BINHH,
Dwcrtflags,
Envbuf,
Null
&sistartinfo,
&prinfo
);

The number of parameters of the function is best not too much, generally speaking 6 or so, a number of function parameters will make the person reading the code look very dizzy, but also not conducive to maintenance. If there are many parameters, use structs to pass parameters. This facilitates the encapsulation of data and the simplicity of the program.

Also good for people who use functions, because if you have a large number of functions, such as 12, the caller can easily mistake the order and number of parameters, and use struct struct to pass parameters, regardless of the order of the parameters.

Moreover, functions can easily be modified, if you need to add parameters to the function, you do not need to change the function interface, just change the structure and function internal processing, and for the program calling the function, this action is transparent.

When writing a function with parameters, the first task is to check the legality of all the parameters passed in. The outgoing parameters should also be checked, which of course should be outside the function, that is, when a function is called, the outgoing value should be checked.

such as input parameters, if the pointer is to determine whether it is empty or illegal

For function return values

If it is a system function, it is necessary to determine the return value to make a corresponding judgment, instead of the default he returns as normal

If you return a Boolean value, you should first determine whether the Boolean value is True or False

If it is a pointer, you should check the legitimacy of the pointer

2, for the use of the choice statement

If it is normal and wrong choice, usually first put the error option in front, because the branch of the error option is relatively small, also can let a person clearly know the various possible error options

For commonly used and infrequently used options, the usual options are usually put in front, which reduces the time that is chosen when the program executes

3, for the error prompt processing

One is the specific situation of the specific analysis, in each error prompt where the code to define the error, although the method is more flexible, but also more irregular, the first is to repeat the error code in the wrong place each time, the other is the same error type may have inconsistent error prompts.

The other is to define all possible error types in the header file by enumeration or const, each variable name is defined by an error description, and a handler error function is defined, the parameter of the function is an error type variable, and a selection statement is defined within the function. Each branch corresponds to a type of error.

4, modify the code of others

when you maintain other people's programs, please do not be very judgmental of the existing procedures to delete or modify. I often see programmers modifying expressions or statements directly on other people's programs. Modify other people's program, please do not delete other people's program, if you feel that other people's program is inappropriate, please comment out, and then add their own handlers, will be, you can not 100% know other people's intentions, so in order to recover, please do not rely on CVS or SourceSafe This version control software, or to others in the source to see you modify the program's intentions and steps.

5, macro

Although, macro execution is very fast (because there is no cost of function calls), but the macro will let the source code to increase the size of the target file, (such as: a line of macros, the program is used in a few places, The macro expands to a great extent, instead of making the program run faster (because the execution file becomes larger and the system is paging frequently at runtime).

6. Static variables

aStaticvariable is a global variable, except that he is a global variable with scope. For example, in a functionStaticvariables,butStaticthe most useful is not here, its greatest effect is to control access, inCif a function or a global variable is declared asStatic, then, this function and this global variable, will only be in thisCfile is accessed, if the otherCfile, call thisCfunction in the file, or use the globalexternkeyword), a link-time error will occur. This feature can be used for data and program secrecy.

7. Function length

A function is usually done with a specific function, and it is forbidden to do many different things in a function. function of the more single, better, on the one hand is conducive to the readability of the function, on the other hand is more conducive to the maintenance and reuse of code, the more the function of a single representation of the function is more likely to provide services to more programs, that is, the more common.

in general, the code in a function is best not to exceed a line or so, The less the better, the best function is generally within the line . There is evidence that the code in a function, if it is more than a line, will have the same or similar code as another function, that is, you can write another function.

Although the invocation of a function has some overhead, it is worthwhile to add some runtime overhead to better maintainability and code reusability than software post-maintenance.

8, hard-coded

It is best not to have a digital " hard code "in the program, such as the size of the array or the number of loops, try not to use numbers directly, but to define constants to use, So you know what this value is for when you use it.

9. Debugging information

program in the development process must have a lot of programmer debugging information. I have seen many project groups, when the development of the program at the end of the launch of the crowd to remove the debugging information in the program, why? Why not set up two versions of the target code like VC + +? One is the debug version, and one is the release version. Those debugging information is so valuable, in the future maintenance process is also very valuable things, how can say delete delete it?

10. String constants

For like

Char *p = "Test";

*p = ' P ';

Such an assignment operation, although it can be compiled normally, but the assignment statement does not work, because "test" is a constant, can no longer be assigned, the compiler will automatically define it as a constant pointer, and at run time, in the VS2008 Environment, if the release mode does not give an error, when running into the assignment statement in debug mode, the program crashes directly. And if two pointers point to the same string constant, the two pointers point to a string of the same address. So to avoid this definition, if you have to define a constant like this, you can use the following format:

const char *p = "Test";

this explicitly declares that P is a constant pointer, and if it is assigned a value the compiler will give an error.

To point a pointer to a generic string, use the following method to

Char *p = new CHAR[5];

p = "Test";

if (p)

{

strcpy (P, "test");

P[0] = _t (' 4 ');

AfxMessageBox (P);

Delete[] p;

p = NULL;

}

The assignment above is normal.

However, if you add the sentence that is commented on above, the problem will occur. Because this statement is equivalent to having p point to a string of "test" constants, instead of pointing to the address assigned to new , the following assignment statement does not work, Because it is now a pointer constant, using delete also does not work because p now does not point to the address assigned to new. and caused a memory leak.

Or

Char A[5] = {0};

strcpy (A, "test");

AfxMessageBox (a);

A[0] = ' 0 ';

AfxMessageBox (a);

Of course, using the string or cstirng class can also avoid the problem above.

11. For reference

After the reference is initialized, the reference always points to the variable, which is equal to the pointer constant, then to the other variable, and to the value of the variable to which the music reference initializes the corresponding variable.

12. String Functions

Strcmp,strlen,strcpy,strcat These string functions cannot manipulate null pointers directly or memory errors will occur directly, so be sure to determine if the pointer is empty before you operate.

13. Definition and initialization

The initialization must have storage space for initialization, and if the declaration has an initialization, it can be treated as a definition, even if the declaration is marked as extern

The header file can only hold variables, function declarations and the definition of inline functions, variables default to extern type, but in advance declaration, by defining a variable in the CPP file, in its corresponding header file with the extern declaration file, and then in the CPP file used in the variable # Include contains the header file of the variable declaration, of course, if you do not want the variable to be accessed by another file, you can add a static prefix to the definition, so that it cannot be accessed by an external file even if it is declared with extern in the header file

14. The difference between a pointer and a reference

1), the reference must be initialized, cannot be null, the pointer can be empty, the reference is assigned to a variable can no longer be assigned, the pointer is arbitrarily changed, so there is no const reference, but the pointer has. The pointer is a dereference, not a reference. Pointers can be nested to use, reference not.

2), when using sizeof, the pointer gets the size of the pointer, the reference is the size of the variable

3), pointers and referenced add and subtract operations are different

15. The difference between an assignment constructor and a copy constructor

1), the copy is to create a new object and assign a value to it, the assignment is to assign a value to an already existing object.

2) When there is a heap allocation pointer within the object, note the difference between a deep copy and a shallow copy. When you need to allocate space for a new object for replication, and then assign the value to it, if you pass only the pointer value, it causes multiple pointers to point to the same piece of memory space, causing a problem with duplicate deallocation. If it is an assignment, it is necessary to determine if it is not the same object, then return directly, if not, release the original memory, then allocate new memory and write the value to the new memory.

3), the parameter of the copy function is a reference, no return value, and the parameter and return value of the assignment function are references. Because the copy function is a constructor, the constructor is not a return value, using a reference instead of a value pass avoids repeating calls to the copy constructor, generating many copies, and most importantly, using value passing will cause an infinite loop recursive invocation of the copy function.

In summary, one of the situations where you need to customize copy constructors and assignment functions is that there are variables in the class that dynamically allocate memory. If the assignment function uses the default function, it causes the original memory address to be compromised, and multiple pointers point to the same piece of memory, causing a duplicate release. The problem of using the default copy function only passes the pointer value past, causing a pointer to point to the same piece of memory, causing a duplicate release.

16. virtual function table

A class without virtual functions has no virtual function table

When allocating memory for a class object, the pointer space that stores the address of the virtual function table is allocated first, and a class has only one copy of the virtual function table in memory, and all objects of that class are called this virtual function table

in vs2008, the first address of a virtual function table is not the address of the first virtual function, and the table stores only the address of the virtual function, not the address of the virtual function is not stored, so different versions of the compiler may not be the same definition

17. Explicit in C + +

in the In C + + , a constructor for a parameter (or a multi-parameter constructor that has a default value other than the first argument) has two functions: the first is the constructor of a formal parameter, the second is the implicit assignment operation function, but sometimes you want to disallow such implicit conversions, you can precede the constructor with the keyword Explicit

18. Type compatibility rules for base classes and derived classes

Pointers to the base class of a derived class cannot directly access the new members in the derived class.

Need to know some common sense that all functions of a class are the only ones stored in the code area. Data members are stored in one copy of each object and stored in the order in which they are declared.
classA has a virtual function in theThe first of the data members of a class is addedVfptr pointer (void** vfptr), which is used to point to a vtable table (an array of function pointers), which stores the addresses of all virtual functions of the current class. In this way, Vfptr becomes a similar member variable exists. When the virtual function is accessed, the vtable table is found through the Vfptr address, and then the function is found to be called. This is to some extent out of the type constraints.
justThe value of the vfptr is different, so the vtable table used when accessing the function member is different, and it is possible to access function members of different classes. The vptr in Class B objects point to Class B's own vtable.
whenWhen Class B inherits the Class A, because there is a virtual function in a, the compiler automatically adds the Vfprt pointer and the vtable table to class B. It can also be understood that Class B inherits from the Vptr pointer member in Class A.
whenA pseudo-cut occurs when a-class pointer points to a Class B object. To know that this process only cuts out those members not in Class A, since Vfptr is inherited from Class A, this amount will remain. The value for Vfptr is not changed and still points to the vtable table of Class B. So accessing the F1 function is addressed through the vtable table of Class B, which is naturally a function of subclasses.
whenThis is the same as when the pointer of Class B points to an object class A, which may be an error when there is a new data member in Class B.
The normal function is subject to type constraints (because there is noThe vptr pointer) uses the pointer of which class to invoke the function, then the class is calledthe function.
In summary, the normal function finds the called function by the type of the object or pointer, and the virtual function locates the function to be called by a pointer.

When a derived class object is assigned to a base-class pointer, the base-class pointer cannot access the new member in the derived class, but when the base-class pointer is coerced to a derived-class pointer, the new member in the derived class can be accessed.

19. Four types of conversions

Reinterpret_cast

Conversions in binary form are generally not

Const_cast

used to remove the const attribute and change the const type pointer to a non- const type pointer, such as:const int *fun ( int x,int y) {}  int *ptr=const_cast<int *> (Fun (2.3) )

Static_cast

Static_cast is actually the implicit conversion and ordinary display forced conversion, no type security checks, so that after the conversion of the call will be problematic, for example, the base class object to the inheritance class pointer, use the pointer to access the new members of the inheriting class will be error, but there is no error in conversion, In the call of the time will be error, there is a great hidden trouble. The type conversion of C language is actually this kind of conversion.

dynamic_cast

The use of dynamic_cast will be the first type check, if not the direct error, will not go to convert, PD1 = dynamic_cast<d*> (pb), if successful then PD1 point to Pb, If the failure is PD1, the statement can be placed in the conditional execution of the conditional statement, and if the expression is 0 if it fails, the execution fails and the processing fails.

note, however, that a virtual function is required in a class that uses dynamic_cast, otherwise it will be an error, because runtime type checking requires run-time type information, and this information is stored in the virtual function table of the class (With regard to the concept of virtual function tables, in detail <inside C + + object model>), only classes that define virtual functions have virtual function tables, and classes that do not define virtual functions have no virtual function tables.

For references, because there is no null reference, it is not possible to use a check policy on a reference that enforces type conversion for pointers, instead, when the conversion fails, it throws a Std::bad_cast exception that is defined in the library header file TypeInfo. You can rewrite the previous example below to use the reference:

void f (const Base &b)

{

Try

{

Const Derived &d = Dynamic_cast<const derived&> (b);

Use the Derived object to which B referred

}

catch (Bad_cast)

{

Handle the fact that the cast failed

}

}

20. Array function parameters

void Func (char str[100])
{
 sizeof (str);//result is 4
}


  Func (char str[100]) function in the array name as a function parameter, in the function body, the array name loses its own connotation, just a pointer, in the loss of its connotation at the same time, it also lost its constant characteristics, can be self-increment, self-reduction and other operations, can be modified.


The meaning of the array name is as follows:
(1) array name refers to a data structure, this data structure is an array;
For example:
Char str[10];
cout << sizeof (str) << Endl;
The output is ten,str refers to data structure char[10].


(2) The array name can be converted to a pointer to its reference entity, and is a pointer constant, can not be self-increment, self-reduction and other operations, can not be modified;
Char str[10];
str++; Compilation error, indicating that STR is not an lvalue

 
(3) when the array name is a function parameter, it is reduced to a normal pointer.

Some programming tips and details for C + +

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.