+ 1

Passed by const reference in constructors C++

I'm learning POO, and I have this simple class: Class Person{ private: Std::string name; Std::string Id; Public: Person(std::string _name, std::string _id) :name(_name), id (_id) { } }; When I used a static analizer in this code, I got this: (Performance) function parameter '_name' should be passed by const reference. (Performance) function parameter '_id' should be passed by const reference. I'm still learning about POO and I don't understand why they should be passed by const reference, if I compile the class I don't have any problem, and if I implement the class it works fine, but I don't understand the notification of the static analyzer. I solved this just adding &_name, &_id, why do I need &, if without the & the class works fine? What is the meaning of that "performance" that I got?

10th Dec 2018, 4:40 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
5 Réponses
+ 5
"function parameter '_name' should be passed by const reference." A short answer would be because a string might contain thousands or even millions of characters in it, therefore, the static analyzer made an assumption that your string might be so big to pass around by copying the whole content instead of an efficient reference. Being constness also make sure that the string won't change (in fact, it doesn't need to be changed in the constructor's body). Person(const std::string &_name, const std::string &_id) is perfectly appropriate there.
10th Dec 2018, 6:26 AM
Babak
Babak - avatar
+ 4
"you should pass every complex* object" Also, STL containers like vectors, map, etc. for the most part, right?
10th Dec 2018, 10:08 AM
Babak
Babak - avatar
+ 3
General rule of thumb is that you should pass every complex* object as const reference (assuming you don't want to change it). When you pass object as value you have to call copy constructor to create temporary object, where with "&" you just create reference, so it saves time with no need of copy constructor. *complex type means just built-in or yours classes.
10th Dec 2018, 9:35 AM
Jakub Stasiak
Jakub Stasiak - avatar
+ 3
Exactly
10th Dec 2018, 10:12 AM
Jakub Stasiak
Jakub Stasiak - avatar
+ 3
I see know why the static anayzers told me about declaring it as const reference, I had no idea the main reason of this, Jakub Stasiak , C++ Soldier (Babak) . Thank you so much! :)
10th Dec 2018, 10:30 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar