Why can a const reference to a string parameter take string literals? String literals, like "hello"
, are not variables, so why is this code valid?
class CVector {
public:
int x, y;
CVector() {};
~CVector() { delete ptr; }
string* ptr;
void doSomething(const string& str) { ptr = new string(str); }
void print() { cout << "\n" << *ptr; }
};
int main()
{
result.doSomething("asdas");
result.print();
return 0;
}
First of all, I thought that references as parameters were used to avoid the copying process and directly access the variable taken as argument(I could still be correct though). But the string literal "asdas" is not a variable, so why can the parameter take string literals as argument? I mean since the parameter str
is a reference, it will become an alias for that entity, right? If so, did the literal just become a variable?
Shouldn't the parameter list consist of string& str
instead of the const reference, so that the literal would be used in the construction of str
?
And doesn't a const reference keep the referenced entity alive for as long as the reference is alive? If so, why would you do that to a literal?