2

I heard c++ doesn't let me use array as function's variable since copying all elements in array could be inefficient. So I have to use pointer instead. That being said, is it better to use pointer of certain object as function's variable whenever possible? Or is there any downside of this method?

edit : I know how array is passed in C++. My questions are :

  1. Is it efficient to use pointer(or reference) when sending class(or structure) object?
  2. Is there any reason not to use pointer(or reference) every time? I saw lot of code which doesn't use pointer when object is small. I mean it is still extra memory usage, so why don't we use pointer in such cases as well?

I've got the answer of 1st question, so could you please answer second question?

  • 1
    If you are talking about single objects then, if necessary, you should use a reference to avoid copying that object when you call the function. A reference is better than a pointer in this case. – john Jul 13 '20 at 10:07
  • 1
    Yes in c++ you usually pass big/expensive objects **by-reference** and small objects **by-value**. by-reference means `const YourClass&` – Sebastian Hoffmann Jul 13 '20 at 10:07
  • 1
    You don't have to use pointers. You can pass C arrays by reference. And in fact, if passing the name of an array, that can decay to a pointer in a function argument, although you should always prefer references to pointers. There is also `std::array`. Whether to use values, pointers, or references depends entirely on context (what the array is of, how large it is, what the function is doing with it, etc.) and has been discussed many times already. This question seems too broad or a clear duplicate. – underscore_d Jul 13 '20 at 10:09
  • Does this answer your question? [How are arrays passed in C++ by reference or value or by pointer?](https://stackoverflow.com/questions/44696363/how-are-arrays-passed-in-c-by-reference-or-value-or-by-pointer) or [Passing an array by reference](https://stackoverflow.com/questions/5724171/passing-an-array-by-reference) or many more. – underscore_d Jul 13 '20 at 10:10
  • My question is why we pass small objects by value. Is there any reason not to use pointer(or reference) everytime? – Suh Myung Kyo Jul 13 '20 at 10:11
  • 3
    For a reference you need to pass something like a pointer. "something like a pointer" is usually 4 or 8 bytes. I.e. if you want to pass a smaller datatype it's cheaper to pass by value. (completely ignoring padding and optimizations here). – Lukas-T Jul 13 '20 at 10:16

0 Answers0