Passing pointers to a C++function

A question about C++. When passing an ordinary variable to a function, a copy of it is created, as I understand it. And what happens when we pass a pointer? Is a copy of the pointer being created or not?

Author: Vlad from Moscow, 2016-12-24

2 answers

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 initialization of the parameter 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 can not be made in any way affect the original argument, unless the type T is a reference type.

Compare the two functions

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

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

And their call

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 calling the function f, 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 exits, and thus the address of the dynamically allocated memory is lost.

The g function has a reference parameter 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 original pointer in a function. For example,

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

The function call will look like

h( &p );
 11
Author: Vlad from Moscow, 2016-12-25 14:25:25

It is being 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.

 7
Author: Vladimir Gamalyan, 2016-12-25 00:36:14