0

If you are passing a large object to a function, say a class containing a large array, is it always better to pass by reference? The idea would be to construct the function so:

template<class T> double foo(T& t){...}

ADDITION AFTER FIRST POST: If I wanted the function to be non-modifying, I would use a const reference.

I could then call the function simply by passing the objects to it:

T large_data = T(1000000);
f(large_data);
eerorika
  • 232,697
  • 12
  • 197
  • 326
Plamen
  • 650
  • 1
  • 8
  • 27

2 Answers2

2

This is the basic idea behind passing an object into a function by reference (with const for immutable objects): you don't want to pass the underlying (large amount of) data and you don't want the messiness (memory management issues, -> and dereference) of a pointer.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • While I agree with you that references are better to express your intetentions I dont understand your complaints about the `->` and `*` operator. There is no more overhead as references are usually implemented as pointers too. – Sebastian Hoffmann Jan 24 '14 at 13:57
  • @Paranaix yes, but it's all done under-the-hood - no need for `t->foo()` or `(*t).foo()` just t.foo(). – Paul Evans Jan 24 '14 at 13:59
  • And? I dont see any overhead? `->` and `*` are some of the most commonly used operators in c++ and nothing special and whether I write `.` or `->` makes no difference at all. Quite the contradictory is the case: IMO `->` states much clearer that a "referenced" object is accessed. – Sebastian Hoffmann Jan 24 '14 at 14:02
  • @Paranaix never mentioned any overhead, just said it was *messy* – Paul Evans Jan 24 '14 at 14:06
1

Generally in C++ for every custom type is better to pass by reference or by pointer. Otherwise, except performance, you could experience problems if your object requires custom copy constructor (and you maybe don't have it implemented, but compiler generated one will do only shallow copy). Also, slicing could happen, etc...