c++ passing arguments by reference and pointer

后端 未结 5 1913
-上瘾入骨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.

提交回复
热议问题