passing object by reference in C++

后端 未结 5 767
有刺的猬
有刺的猬 2020-12-02 07:56

The usual way to pass a variable by reference in C++(also C) is as follows:

void _someFunction(dataType *name){ // dataType e.g int,char,flo         


        
相关标签:
5条回答
  • 2020-12-02 08:29

    One thing that I have to add is that there is no reference in C.

    Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case

    If there was some "reference" keyword instead of & you could write

    int CDummy::isitme (reference CDummy param)
    

    but this is C++ and we should accept it advantages and disadvantages...

    0 讨论(0)
  • 2020-12-02 08:30

    Ok, well it seems that you are confusing pass-by-reference with pass-by-value. Also, C and C++ are different languages. C doesn't support pass-by-reference.

    Here are two C++ examples of pass by value:

    // ex.1
    int add(int a, int b)
    {
        return a + b;
    }
    
    // ex.2
    void add(int a, int b, int *result)
    {
        *result = a + b;
    }
    
    void main()
    {
        int result = 0;
    
        // ex.1
        result = add(2,2); // result will be 4 after call
    
        // ex.2
        add(2,3,&result); // result will be 5 after call
    }
    

    When ex.1 is called, the constants 2 and 2 are passed into the function by making local copies of them on the stack. When the function returns, the stack is popped off and anything passed to the function on the stack is effectively gone.

    The same thing happens in ex.2, except this time, a pointer to an int variable is also passed on the stack. The function uses this pointer (which is simply a memory address) to dereference and change the value at that memory address in order to "return" the result. Since the function needs a memory address as a parameter, then we must supply it with one, which we do by using the & "address-of" operator on the variable result.

    Here are two C++ examples of pass-by-reference:

    // ex.3
    int add(int &a, int &b)
    {
        return a+b;
    }
    
    // ex.4
    void add(int &a, int &b, int &result)
    {
        result = a + b;
    }
    
    void main()
    {
        int result = 0;
    
        // ex.3
        result = add(2,2); // result = 2 after call
        // ex.4
        add(2,3,result); // result = 5 after call
    }
    

    Both of these functions have the same end result as the first two examples, but the difference is in how they are called, and how the compiler handles them.

    First, lets clear up how pass-by-reference works. In pass-by-reference, generally the compiler implementation will use a "pointer" variable in the final executable in order to access the referenced variable, (or so seems to be the consensus) but this doesn't have to be true. Technically, the compiler can simply substitute the referenced variable's memory address directly, and I suspect this to be more true than generally believed. So, when using a reference, it could actually produce a more efficient executable, even if only slightly.

    Next, obviously the way a function is called when using pass-by-reference is no different than pass-by-value, and the effect is that you have direct access to the original variables within the function. This has the result of encapsulation by hiding the implementation details from the caller. The downside is that you cannot change the passed in parameters without also changing the original variables outside of the function. In functions where you want the performance improvement from not having to copy large objects, but you don't want to modify the original object, then prefix the reference parameters with const.

    Lastly, you cannot change a reference after it has been made, unlike a pointer variable, and they must be initialized upon creation.

    Hope I covered everything, and that it was all understandable.

    0 讨论(0)
  • 2020-12-02 08:32

    A reference is really a pointer with enough sugar to make it taste nice... ;)

    But it also uses a different syntax to pointers, which makes it a bit easier to use references than pointers. Because of this, we don't need & when calling the function that takes the pointer - the compiler deals with that for you. And you don't need * to get the content of a reference.

    To call a reference an alias is a pretty accurate description - it is "another name for the same thing". So when a is passed as a reference, we're really passing a, not a copy of a - it is done (internally) by passing the address of a, but you don't need to worry about how that works [unless you are writing your own compiler, but then there are lots of other fun things you need to know when writing your own compiler, that you don't need to worry about when you are just programming].

    Note that references work the same way for int or a class type.

    0 讨论(0)
  • 2020-12-02 08:43

    Passing by reference in the above case is just an alias for the actual object.

    You'll be referring to the actual object just with a different name.

    There are many advantages which references offer compared to pointer references.

    0 讨论(0)
  • 2020-12-02 08:47

    What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &) aren't called using actual addresses, i.e. &a.

    The simple answer is that declaring a function as pass-by-reference:

    void foo(int& x);
    

    is all we need. It's then passed by reference automatically.

    You now call this function like so:

    int y = 5;
    foo(y);
    

    and y will be passed by reference.

    You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :

    #include <iostream>
    using namespace std;
    
    class CDummy {
    public:
        int isitme (CDummy* param);
    };
    
    
    int CDummy::isitme (CDummy* param)
    {
        if (param == this) return true;
        else return false;
    }
    
    int main () {
        CDummy a;
        CDummy* b = &a;             // assigning address of a to b
        if ( b->isitme(&a) )        // Called with &a (address of a) instead of a
            cout << "yes, &a is b";
        return 0;
    }
    

    Output:

    yes, &a is b
    
    0 讨论(0)
提交回复
热议问题