c++ passing arguments by reference and pointer

19,126

Solution 1

The pointer and the reference methods should be quite comparable (both in speed, memory usage and generated code).

Passing a class directly forces the compiler to duplicate memory and put a copy of the bar object on the stack. What's worse, in C++ there are all sort of nasty bits (the default copy constructor and whatnot) associated with this.

In C I always use (possibly const) pointers. In C++ you should likely use references.

Solution 2

In any reasonable way passing by reference will probably result in code involving addresses of objects. However, the main issue is that using references is more idiomatic C++ and should be the preferred style; you should really not be seeing raw pointers a lot at all in your own code.

Also note that passing by value and by reference is fundamentally different in the sense that passing by reference allows the callee to modify the argument. If anything, you should be comparing f(bar) with f(const bar &).

Solution 3

Pointers and references differ syntactically, and usually are identical in runtime and code generation. As to older compilers... I knew one bug in Borland 3 C++ DOS compiler: it cached an int value (passed by reference) in a register, modified it and did not change the original value in memory. When passing by pointer an equivalent code worked as expected.

However, I don't think any modern compiler may do such strange things (and Borland 5 has fixed the issue)

As to code style (apart from pointers vs. smartpointers tradeoff), I usually use references if the address can not be NULL by function contract, and use pointers otherwise.

Share:
19,126
VirusEcks
Author by

VirusEcks

i'm A relativly new c++ developer my previous developing/scripting languages experience : vb fb perl lua mIRC html don't blame me if you got infected while reading my biography :P

Updated on June 19, 2022

Comments

  • VirusEcks
    VirusEcks about 2 years

    in c++

    class bar
    {
        int i;
        char b;
        float d;
    };
    
    void foo ( bar arg );
    void foo ( bar &arg );
    void foo ( bar *arg );
    

    this is a sample class/struct and functions
    i have some Qs

    • what's the difference between 1st and 2nd way of passing the argument in 'asm', size, speed ?
    • how the arguments are passed to the functions foo in each case ( in case of pointer i know the pointer is pushed on the stack )
    • when passing arguments, in terms of efficiency at ( speed, size, preferability ) which is better ?
    • what's the intel 'asm' syntax that corresponds each of the ways of passing arguments ?

    i know what most say about "it doesn't matter on modern compilers and CPUs" but what if we're talking about Old CPUs or compilers?

    thanks in advance