0

I am a C++ newbie and I am working on a program that simulates a phonebook. Now, for the insert operation, function is defined as follows:

void PhoneBook::insert(const string& name, const string& number)

But it still works and inserts the contact as well if I remove the reference symbols. So, I am a little confused here, why do I need them?

void PhoneBook::insert(const string name, const string number)
Yazgan
  • 151
  • 11

1 Answers1

2

void PhoneBook::insert(const string name, const string number)

Here you are constructing new strings with copy of all data. This is heavy operation.

void PhoneBook::insert(const string& name, const string& number)

Here you are passing reference to string (address of string), size of which is usually 4 or 8 bytes, based on platform, which is very light operation.

Also, when you pass reference, you are allowed to interact with object, which you are passed to function.

Rule of thumb - always pass by const reference, if variable is bigger than 8 bytes and you dont require explicit copy of object.

Starl1ght
  • 4,422
  • 1
  • 21
  • 49
  • Thanks, I'll work on the given duplicate link. – Yazgan Dec 01 '16 at 10:03
  • This fails to address the fundamental semantic difference between referencing a foreign object and creating a new copy to hold onto. Optimization concerns, which seem to be all the craze with reference parameters, come way later down the line. – Quentin Dec 01 '16 at 10:05