Let’s say I have a class:
class String
{
public:
String(char *str);
};
And two functions:
void DoSomethingByVal(String Str);
void DoSomethingByRef(String &Str);
If I call DoSomethingByVal like this:
DoSomethingByVal("My string");
the compiler figures out that it should create a temporary String object and call the char* constructor.
However, if I try to use DoSomethingByRef the same way, I get a “Can’t convert parameter from ‘char *’ to ‘String &'” error.
Instead, I have to explicitly create an instance:
DoSomethingByRef(String("My string"));
which can get preety annoying.
Is there any way to avoid this?
You need to pass by const reference:
For:
In this situation the compiler first creates a temporary variable. Then the temporary variable is copy constructed into the parameter.
For:
In this situation the compiler creates a temporary variable. But temporary variables can not be bound to a reference they can only be bound to a const reference so your original function can not be called. Note the std::string objects constructor takes a const reference is the parameter to the copy constructor and that is why the first version works as the temporary is bound to the const reference parameter of the copy constructor only.