c++ passing arguments by reference and pointer

后端 未结 5 1902
-上瘾入骨i
-上瘾入骨i 2020-12-03 09:59

in c++

class bar
{
    int i;
    char b;
    float d;
};

void foo ( bar arg );
void foo ( bar &arg );
void foo ( bar *arg );

this i

相关标签:
5条回答
  • 2020-12-03 10:26

    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.

    0 讨论(0)
  • 2020-12-03 10:34

    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 &).

    0 讨论(0)
  • 2020-12-03 10:36

    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.

    0 讨论(0)
  • 2020-12-03 10:43

    If you consider that it's good practice to validate pointer parameters before using them then, yes, pointers introduce extra overhead since references don't require such testing.

    0 讨论(0)
  • 2020-12-03 10:46

    Function foo can modify arg in cases 2 and 3. In first cases compiler could optimize copy creation, so it is very hard to compare cpu and memory usage.

    0 讨论(0)
提交回复
热议问题