C++: Argument Passing “passed by reference”

前端 未结 4 1723
忘了有多久
忘了有多久 2020-11-27 16:24

I understand as with any other variable, the type of a parameter determines the interaction between the parameter and its argument. My question is that what is the reasonin

4条回答
  •  星月不相逢
    2020-11-27 16:54

    This article helped me a lot.

    Please forget about pointers for now. And take this with a grain of salt.

    A reference is the object. When you pass by reference, you pass the object.

    When you pass by value, you pass a copy of the object; another object. It may have the same state, but it is a different instance; a clone.

    So, it may make sense to pass by reference if you:

    • need to modify the object inside the function
    • do not need (or want) to modify the object, but would like to avoid copying it just to pass it to a function. This would be a const reference.

    And it may make sense to pass by value if you:

    • want to start from an identical twin, and leave the original twin undisturbed
    • do not care about the cost of copying the object (for example, I would not pass an int by reference unless I wanted to modify it).

    Here, have a look at this code:

    #include
    
    struct Foo {
      Foo() { }
      void describe() const {
        std::cout<<"Foo at address "<

    And compile it like this: g++ example.cpp

    Run it: ./a.out

    And check the output (the actual addresses may be different in your computer, but the point will remain):

    Original Foo
    Foo at address 0x7fff65f77a0f
    called byreference
    Foo at address 0x7fff65f77a0f
    called byvalue
    Foo at address 0x7fff65f779f0
    

    Notice how the called byreference address is the same as the Original Foo address (both are 0x7fff65f77a0f). And notice how the called byvalue address is different (it is 0x7fff65f779f0).

    Take it up a notch. Modify the code to look as follows:

    #include
    #include // for sleeping
    
    struct Foo {
      Foo() { }
      Foo(const Foo&) {
        sleep(10); // assume that building from a copy takes TEN seconds!
      }
      void describe() const {
        std::cout<<"Foo at address "<

    Compile it the same way, and notice the output (comments not in the output; included for clarity):

    Original Foo
    Foo at address 0x7fff64d64a0e
    called byreference
    Foo at address 0x7fff64d64a0e # this point is reached "immediately"
    called byvalue # this point is reached TEN SECONDS later
    Foo at address 0x7fff64d64a0f
    

    So, the code is meant to exaggerate the cost of a copy: when you called by reference this cost was NOT incurred. When you called by value you had to wait for ten seconds.

    Note: my code was compiled in OS X 10.7.4 using GCC 4.8.1. If you are in windows you may need something different from unitsd.h to make the sleep call work.

    Maybe this helps.

提交回复
热议问题