Rick Helmus wrote:
Hello all
In a few classes I have overloaded functions for C style strings and
STL strings like this
class SomeClass
{
void f(const char *s);
void f(const std::string &s);
};
At some point I forgot to include a C string function version in a
class, but noticed it all worked fine with const char *'s anyway...
In other words; const std::string &str = "blah"; works (a non const
reference won't). AFAIK this means it's a reference directly to a const
char *,
No, it's a const reference to a std::string, just like it says it is.
The tricky bit is understanding *which* std::string it is a const
reference to, since at first glance there is noo std::string there.
can someone explain me why this would work?
#include <string>
class SomeClass
{
public:
// Oops! Forgot to implement void f(const char *s);
void f(const std::string &s) { /* do stuff ... */ }
};
int main()
{
SomeClass sc;
sc.f("blah");
}
When sc.f("blah") is called, an unnamed temporary std::string object is
created by the compiler and contructed using the std::string
constructor that takes a const char*, in this case using the value
"blah". The formal parameter s in the function is a const std::string&
which is bound to this unnamed temporary std::string. At the end of the
statement sc.f("blah"); the unnamed temporary std::string is destroyed.
const references may be bound to temporary objects. non-const
references may not, which is why you found that using a std::string&
rather than a const std::string& did not work.
Gavin Deane