Function parameter passing mechanism C / C ++ are

The function of the parameter of interest can look

 

First, the basic theory of parameter passing mechanism functions 

  Parameter passing mechanisms function in nature is to call the called function and the method (process) for communication problem occurs when calling a function (procedure). The basic argument passing mechanisms in two ways: the value passed and passed by reference. The following discussion of the function calls other functions, said main tuning function, the function is called to the called function.

  Value passed ( VpassL-by-value ) during the formal arguments of the function transferred as a local variable called function processing, i.e., open space in the stack memory to store values into the argument to the calling function, such that He became a copy of the argument. Characteristic value is passed in the form of operating parameters of the called function are carried out as a local variable, the value does not affect the calling function argument variables.

  Reference transmission (pass-by-reference) process, the called function in the form of local variables as parameters although opened in the stack memory space, but then is stored into the address to the calling function argument variables. Is any operation parameter of modulation functions are treated as indirect addressing, i.e. access the argument in the calling function by the variable address stored in the stack. Because of this, any operation is made on the parameter adjustment function argument variables are influenced in the calling function.

Two,  C language function parameter passing mechanism

  In the C language, the value passed is the only parameter passing mechanism available. But as far as I know, due to the pointer variable as a function of the impact parameter, there are many friends also believe that this case is passed by reference. This is wrong. Consider the following code:

int swap(int *x, int *y)

{

int temp;

temp = *x; *x = *y; *y = temp;

return temp;

}

void main()

{

int a = 1, b = 2;

int *p1 = &a;

int *p2 = &b;

swap(p1, p2)

}

  Function swap two pointer variables as parameters, when the main () call swap , the value passed by way of the variable pointers P1 , P2 values (i.e. the variables A , B 's address) on the swap of the stack in the form of parameters X , Y memory cell in the open.

 Here we get the following:

  1 .  Stack memory area of the main process is the calling function and the called function to communicate.

  2 .  C language parameters from right to left into the stack.

  3 .  Stack area structure is used as modulation functions:

    Local variables (such as TEMP )

    Return address

    Function Arguments

    Low address

    High Address

  4 .  By the calling function to clean up the stack after the call.

  5 .  Return value of the function is generally in register.

  Still need to add a couple of points here: First, the parameters of the way into the stack. For the internal type, because the compiler knows the type of each variable so that the size of the memory used directly push instruction; for custom types (e.g., structure mode), using byte transfers to the destination (stack area) address from a source address stack . Second, why the function return value is generally placed in the register , which is mainly to support interrupt; if placed in the stack is possible because of interruption is covered. Third, if the return value of the function of large , the return value from the stack to the address storage unit (provided by the calling function to push the called function before calling this address) byte transfers, to achieve the purpose of the return. For the second and third points, " Thinking in C ++ " book in the first 10 chapters have better explained. Fourth, an obvious conclusion, if the return of local variables in the called function address is pointless; because local variables stored in the stack, the stack will be cleaned after the end of the call, the address becomes invalid.

Three,  C ++ language function parameter passing mechanism

   As we all know, in the c There are three ways when you call the function parameter passing ++ in:

 ( 1 ) call-by;

 ( 2 ) pass-call (transfer pointer);

 ( 3 ) passed by reference;

    In fact, there is a way of passing parameters, it is a global variable transfer mode. Here the "global" variable and is not necessarily true global, direct access to all the code, as long as the scope of this variable enough to visit these two functions can, for example, two members of a class of functions can be used achieve a member variable parameter passing, or use the static keyword to define, or use the namespace restrictions, etc., but here's member variables in this sense it can be called a "global" variable (no other than the "global" more a good word to describe). Of course, you can use real global variables outside of a class to implement parameter passing, but sometimes there is no need, from an engineering perspective, the scope of the smaller the better. What are the advantages of it this way?

 efficient!

 Indeed, this efficiency is all the parameters passed in the most efficient way, to be higher than the previous three ways, no matter under what circumstances. However, this approach has a fatal weakness, that is support for multithreading is not good, if the result of two processes at the same time call the same function, and the parameters are passed through the global variable, the function can not always get what you want .

 

 The following discussion of the above three functions, respectively, and then transfer mode.

    1.  From the function. When the value passed by the pass, an argument is copied, and then use the functions in the body, modify the function of the variable parameter value is altered in vivo is a copy of the argument, the argument itself is not changed, so if you want modifying argument value in the function call, the value is not passed to an end, then only use reference or pointer passed. For example, to achieve exchange of two values.

 void swap(int a  int b) 

 void main(){

     int a=1  b=2 

     swap(a b) 

 }

 Thus, the main () function in the ab values was not actually exchange, the exchange can only be used if you want to pass a pointer or reference transmission, such as:

 void swap(int pa  int pb) 

 or

 void swap(int&  ra  int&  rb)

 

   2. From the transmission efficiency. Transmission efficiency here, it is that the code is called function call arguments passed to the called function within the process , as the above code, the process is the function main () in ab transfer function to the swap () in the process . This efficiency can not be generalized. For the built- int char short long float like 4 in terms of the type of data bytes or less, need to pass only when actually transmitting . 1 - 4 bytes, while passing in pointer 32 bit cpu passed is 32 pointer bits . 4 bytes are a command, and the pointer value is passed transmission efficiency in this case is the same, is transmitted double long long other 8 bytes of data, the 32 -bit cpu , which is passed passing a pointer value efficiency than slower, because . 8 bytes requires 2 to take complete times. In the 64 -bit cpuOn traditional values ​​and pass-efficiency is the same. Besides passed by reference, this depends on the compiler specific implementation, passed by reference implementation is the most obvious use of pointers, pointers and efficiency in this case is the same, and the compiler can optimize, in some cases, direct addressing the way, in which case, the efficiency faster than call-by-call and pass-by, and it says the use of global variables passed by quite efficient.

     Besides custom data type, class struct defined data types. These data types are transmitted during temporary object value generated call to the constructor is executed, and when the destructor performs temporary object is destroyed, if the task more constructors and destructors executed, or relatively large size objects passed, then the call-by consumption is relatively large. In this case, the use of pass-calling and using most of the next call by reference efficiency considerably, as noted above, in some cases passing references may be optimized, the overall efficiency of slightly higher pass-call.

    3.  From a performance perspective. The efficiency here refers to the efficiency of performing the function is called the body. Because a call-by, when values are passed to the function body, temporary objects generated after the execution of all tasks are performed by the direct addressing mode, and the reference pointer and in most cases is based on indirect addressing modalities of implementation, so the actual efficiency will be lower than the call by value. If the function of the variable parameters passed over the body to operate more frequently, the case of performing the addition of the total number, pass-by-reference parameters in the call and in most cases will result in obvious passing efficiency losses.

 

 Integrated 2 , 3 in both cases, the efficiency of specific binding to the actual situation, to select the function performed by the resource consumption and the consumption of the body and Comparative transfer process which case appropriate. And references ratio, efficiency is always passed by reference is not lower than the efficiency of delivery and passing a pointer pointer is passed, so in this sense c prioritize use pass by reference instead of a pointer parameter passed ++.

    4.  From the type of security terms. Transmitting the reference value is passed perform strong type checking during the transmission parameters, and pass a pointer type checking is weak, in particular, if the parameter is declared as a  void  , it is substantially free of type checking, as long as the pointer, the compiler considered legitimate, so this gives bug produces manufacturing opportunities, the program is somewhat less robust, if not necessary, to use the value passed and passed by reference, not the best pointer is passed, better use of compiler type checking so that we have fewer opportunities for error, in order to increase the robustness of the code.

 There is a special case, is the case of multi-state, if the parameter is a parent class is a subclass of the argument, the value of the time during the transmission, the configuration of only part of the temporary parent object construction, is a pure parent class object, and no portion of any specific class constructor, as do have virtual destructor, but no virtual constructor, it is to be noted. If you want to get some subclass-specific behavior by calling the virtual function in the called function, which can not be realized.

 5.  From the parameter checking speaking. A robust function, the parameters always passed to the parameter check to ensure the legitimacy of the input data, to prevent damage to data in the control program and run better in the desired direction, using the value in this case transmission ratio use the pointer passed much safer, because you can not pass a nonexistent value of the parameter value or reference parameters, it is possible to use a pointer, is likely to be coming from an illegal address (not initialized, already point to delete out pointer to the object, etc.). Therefore, using the values passed by reference pass and make your code more robust, in particular using the references or use, the simplest principle is to see a transfer is not built-in data type of built-in data type precedence value is passed, for custom data types, in particular the transmitting large objects, use reference.

    6.  From the flexibility. Undoubtedly, the pointer is the most flexible, because the pointer image may be passed in addition to transmitting the value and pass an object as a reference of a particular type, but can also pass a null pointer, do not pass any objects. This advantage makes it come in handy pointer, such as a standard library time () function, you can pass a pointer to it, to fill the time value to a specified address, you can also pass a null pointer as long as the return value .

 

We discuss the advantages and disadvantages of the four items above transfer mode, and then discuss below some common techniques useful in the parameter transfer process.

 1. const keyword. When your parameters as input parameters, you do not always want your input parameters are modified, or logic errors may occur, then you can add parameters before the function declaration const keyword, to prevent accidental changes in the realization function input, for the use of your code programmers can also tell them that this is an input parameter, without adding const argument keywords may also be output. For example strlen , you can declare

     int strlen(char str) 

 Certainly no problem on the function, but you want to tell people to use this function, the parameter str is an input parameter, which points to the data can not be modified, this is what they expect, it would not someone want to ask people to give him when counting money, there are sheets of 100 to become the 10 blocks, or turned into real money counterfeit money, they want a guarantee that the function will not destroy any of your data, you can make a statement as follows they assured:

     int strlen(const char str) 

 Could you give str itself does add a limit, if the address is changed the number of results was not wrong yet? Gotta give a little freedom, so long as it helps you count the money line, why not mind how he counted it? Do not destroy your money ok , and if given str a limit, there will be a problem, according to the above statement, it can be achieved:

   int strlen(const char str)

 {    int cnt 

 if( !str) return 0 

      cnt = 0 

      while( (str++) ){

         ++cnt 

     }

     return cnt 

 }

 However, if you deliberately change statement

     int strlen(const char const str) 

 The above function certainly can not run, can only switch to other implementations, but this is not too necessary. As long as we protect our money line, if it does not count, the next time I do not let the number of times, and back to personal wants.

 

For member functions, if we want to show to the client code, said a member function does not modify the value of the object, it will only read certain content, you can also add a function declaration in the const.

 class    person

 {......

   public:

     unsigned char age (void) const //  see const can rest assured, this function will certainly not modify m_age

   private:

     unsigned char m_age //  I think this type is long enough, if that does not change can be changed to unsigned long

 }

     2.  defaults. Personally think to add a default parameter value is a very handy feature, very easy to use, so you can define a function of several parameters have, then those commonly used parameters to some default value, the client code If you think those defaults exactly what they want, when you call the function only need to fill out the necessary arguments on the line, very convenient, thus eliminating the need for several overloaded functions trouble. But I do not understand c # why this feature to get rid of, and may be for security, this requires arguments to the function assigned to be displayed every time the function is called. So pay attention, this is a double-edged sword, if you want to use the knife strokes with opponents resorting to violence, is likely to hurt yourself.

    3. The order of the parameters. When the function name with a different parameter, if the same parameters as possible should parameter in the same position, to facilitate the client code.

c ++  frequently used reference is constant, as will swap2 to:

    Swap2(const int& x; const int& y)

  The time reference can not modify the contents of the address pointed to in the function, specifically, X and y can not appear in the " = " left.

 

Transfer from http://blog.chinaunix.net/uid-21411227-id-1826834.html

 

Guess you like

Origin www.cnblogs.com/erichyd/p/11366601.html