-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Issue by RobinPetit
Saturday Mar 12, 2016 at 00:01 GMT
Originally opened as https://github.com/ulb-infof209/Group5/issues/96
I see that there are still many places where const references should be used instead of copy in parameters.
In general, you should think this way:
let f be a function taking a parameter p. If p is not a primitive type (int, float, char, etc.) then two choices are available First is using a reference. The advantage is that a reference is way faster because less memory is set on the stack and no copy constructor is called. So if the parameter is read-only, it is better to use a const reference. Second choice is copying the variable to create the parameter. It is slower but it is necessary if the parameter is intended to be modified without changing the original value.
What should be kept in mind while coding is that when you send a std::string to be displayed, use a const reference, when you send a std::vector or std::array to be read at some predetermined indices, use a const reference, if you send a variable which will be modified and it is wanted, then use a non-const reference.
On the other hand, if you send a container which will be modified in the function but should be kept in its original state, pass by copy.
Some examples:
// const reference because the string is only read so no need to copy it
void displayMessage(const std::string& message);
// const reference because \a effects is only read (to be copied in
// an attribute in this very situation) so no need to copy it
Card::Card(cardId id, const EffectsCollection& effects);
// non-const reference because \a transmission is modified
// (by operator `>>` for instance) and it is wanted:
// after calling this method, we want the integer to be removed
// from the packet.
sf::Uint32 getUint32FromPacket(sf::Packet& transmission);
// Don't use references so that a new vector is created, and this
// particular parameter can be shuffled and then returned
// without affecting the rest of the code
std::vector<Card *> shuffleDeck(std::vector<Card *> cards)
{
std::shuffle(cards.begin(), cards.end(), ...);
return cards;
}This is not the most important thing in the world, but I thought it was important to tell it one more time and precise the reason why we (@TheoVerhelst and I) keep telling you to use them.