A 1C ++ object constructor:
Create an object in two steps: first obtain the memory required for the object, and then execute the constructor on the memory. When the constructor constructs this object, the constructor is also divided into two steps: first execute initialization (through the initialization list), then execute the constructor's function body ..... This means that it is a waste to assign values to the member variables in the constructor. The initialization member variables are assigned to the member variables through the initialization list of the constructor, instead of initializing In the constructor body, because these member variables have been initialized once when the constructor body is started.
Class Aclass
{Public:
Aclass ():
I (10), name ("unnamed ")
// Preliminary trial list
{
......
}
PRIVATE:
Int I;
String name;
}
2 object creation/destruction creating and destruction objects often become a program performance bottleneck. Therefore, it is necessary to explore and avoid the generation of temporary objects.
A simple and common method to reduce object creation and destruction is to change all values to reference or constant reference in function declaration.
Int Foo (Object A); // if the value is passed, a local object (copying the original object) is generated. After the call is completed, the copied local object is destroyed.
Int Foo (Object & A); // the address of the original object passed in. All changes in the function body are made to the original object.
Int Foo (const object & A); // constant reference transfer, input the address of the original object, and define it as a constant. In this way, the function cannot be modified but can only be read from the original object.
Object foo2 (Object A); // two temporary objects are generated. One is the value transfer, and the other is the return value.
3. Non-built-in objects
A tries its best to delay the creation of an object until it has been precisely known its valid state, which can reduce the generation of temporary objects.
Aclass c = a + B; better
Aclass C;
C = A + B;
B operator + = no temporary object is generated, and the performance will be better than operator +. Similarly, for-= and -.....
C. If the program semantics is correct, I ++ should be used more than ++ I. For -- I and I --.
4. lifecycle of a temporary object
String A, B;
Const char * STR;
.................
If (strlen (STR = (a + B). c_str ()> 5)
{Printf ("% s \ n", STR );}
The running result of this program is unpredictable, because the life of the temporary object that stores the value of A + B also ends after its longest statement ends. When printf is executed, the temporary object no longer exists. The str in the string content points to a piece of memory that has been withdrawn. The result is unpredictable.
5. Correct Use of inline functions