Plamen
Plamen

Reputation: 660

C++ passing by reference

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);

Upvotes: 0

Views: 122

Answers (2)

Paul Evans
Paul Evans

Reputation: 27577

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.

Upvotes: 2

user3104842
user3104842

Reputation:

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

Upvotes: 1

Related Questions