Question on C ++. When a normal variable is passed to a function, a copy of it is created, as I understand it. And what happens when we pass the pointer? Is there a copy of the pointer or not?

    2 answers 2

    If you have a function declared with a parameter, such as

    void f( T t ); 

    where T is some type and this function is called with some expression passed to it as an argument, like

     f( exp ); 

    then the parameter initialization can be represented as follows

     void f( /* T t */ ) { T t = exp; //... 

    that is, a parameter is a local variable of a function that is initialized by the expression that is passed to the function as an argument. Therefore, changes to the parameter have no effect on the original argument if only type T not a reference type.

    Compare two functions

     void f( int *p ) { p = new int( 10 ); } void g( int * &p ) { p = new int( 10 ); } 

    and their challenge

     int main() { int *p = nullptr; f( p ); if ( p == nullptr ) std::cout << "p is equal to nullptr" << std::endl; else std::cout << "p is not equal to nullptr" << std::endl; g( p ); if ( p == nullptr ) std::cout << "p is equal to nullptr" << std::endl; else std::cout << "p is not equal to nullptr" << std::endl; delete p; } 

    In this example, when a function f is called, there is a memory leak, since the memory allocated in the function is not released. The function parameter — the local variable p — is deleted when the function leaves, and thus the address of the dynamically allocated memory is lost.

    The function g parameter has a reference type, that is, this reference to the argument passed to the function. Therefore, the function deals with the original argument and changes it in its body, assigning it the address of the allocated memory.

    You can also pass a pointer to a pointer if you want to change the source pointer in the function. For example,

     void h( int **p ) { *p = new int( 10 ); } 

    The function call will look like

     h( &p ); 

      It is created.

      Inside the function, you can assign a different value to the pointer and this will not affect the external variable.

       #include <iostream> void foo(int* p) { p = nullptr; std::cout << "inside: " << p << std::endl; } int main() { int v; int* p = &v; std::cout << "before: " << p << std::endl; foo(p); std::cout << "after: " << p << std::endl; } 

      before: 0x7ffd4a1eba94
      inside: 0
      after: 0x7ffd4a1eba94

      Working example