I was wondering about the logic in this function declaration:
CMyException (const std::string & Libelle = std::string(),...
What is the point of using a variable by reference? Usually you pass a variable by reference whenever it may be modified inside... so if you use the keyword const
this means it'll never be modified.
This is contradictory.
May someone explain this to me?
Actually reference is used to avoid unnecessary copy of the object.
Now, to understand why const
is used, try this:
std::string & x= std::string(); //error
It will give compilation error. It is because the expression std::string()
creates a temporary object which cannot be bound to non-const reference. However, a temporary can be bound to const
reference, that is why const
is needed:
const std::string & x = std::string(); //ok
Now coming back to the constructor in your code:
CMyException (const std::string & Libelle = std::string());
It sets a default value for the parameter. The default value is created out of a temporary object. Hence you need const
(if you use reference).
There is also an advantage in using const reference : if you've such a constructor, then you can raise exception like this:
throw CMyException("error");
It creates a temporary object of type std::string
out of the string literal "error"
, and that temporary is bound to the const
reference.
Some arguments might use quite some memory. If you pass an argument as value it will be copied and the copy will be passed to the method.
Passing them as reference will only pass the pointer to the method which is faster and saves the memory for the copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With