reference memory c++

qbendm 0 Reputation points
2023-09-27T12:37:16.27+00:00

Do ‘reference’ allocate memory in Visual Studio C++? Everyone has different opinions. Please tell me the difference between pointer and reference. If you don't need space to store addresses, how can you know and use them?

Developer technologies C++
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-09-27T20:25:37.3366667+00:00

    a pointer variable is a variable that contains the address of a memory location. a reference variable is an alias for a variables address (&<variable name>). when used in an expression, is the same as a pointer (*<variable name>).

    a pointer variable is a value type the size of an address.

    the compiler decides if a reference variable takes memory (no need, its an alias to a real variable).

    void swap(int& x, int& y) {
       int temp;
       temp = x; /* save the value at address x */
       x = y;    /* put y into x */
       y = temp; /* put x into y */
    }
    
    int main () {
       int a = 100;
       int b = 200;
       int& c = a; //c is alias for a
    
       c = 300;  // a = 300;
     
       // pass a & b by reference
       swap(a, b); //a = 200, b = 300
    }
    
    void swap(int* x, int* y) {
       int temp;
       temp = *x; /* save the value at address x */
       *x = *y;   /* put y into x */
       *y = temp; /* put x into y */
    }
    
    int main () {
       int a = 100;
       int b = 200;
       int *c = &a; // c pointer to a
    
       *c = 300;    // a = 300   
    
       // pass a & b by address
       swap(&a, &b);  //a = 200, b = 300
    }
    
    0 comments No comments

  2. didier bagarry 160 Reputation points
    2023-09-27T20:49:10.79+00:00
    • A reference can be in an object, in this case it must be implemented as an address stored in the object.
    • A reference can be a parameter of a function, here the reference need also to store an address.
    • A reference can be a local variable. In this case, the pointer is not needed for example if the reference is initialized by a l-value. The reference is then just an alias of a hidden variable.
    Object  x[2];
    Object&  y = x[0];
    

    Here using y, is an immediate use of x[0]. No pointer is needed.

    • In the case of an inline function, here too the transmission of an address can be avoided, the reference is an alias of the variable transmitted.

    So behind a reference, sometime there is an hidden pointer, sometimes not.

    And sizeof(reference) is always same as sizeof(referenced_object) and &reference is always &referenced_objet, so cannot be used to test how the reference is implemented.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.