Question

i just wrote a function:

void doSomeStuffWithTheString(const std::string& value) {
...
std::string v = value;
std::cout << value.c_str();
...
}

but then i call this with

doSomeStuffWithTheString("foo");

and it works. So i would have thought that this to work (a const char* to initialise a implicit instance of std::string) the value would have to be passed by value, but in this case is passed by (const) reference.

Is by any chance a implicit temporal std::string instantiated from const char* when the reference is const? if not, then how this possibly work?

EDIT

what happens if the function is overloaded with

void doSomeStuffWithTheString(const char* value);

which one will choose the compiler?

Was it helpful?

Solution

The std::string type has an implicit conversion (via constructor) from const char*. This is what allows the string literal "foo" to convert to std::string. This results in a temporary value. In C++ it's legal to have a const & to a temporary value and hence this all holds together.

It's possible to replicate this trick using your own custom types in C++.

class Example {
public:
  Example(const char* pValue) {}
};

void Method(const Example& e) {
  ...
}

Method("foo");

OTHER TIPS

Yes, a temporary std::string is constructed from the string literal.

Exactly, using std::string default constructor

"the value would have to be passed by value, but in this case is passed by (const) reference."

There is a C++ feature where it is possible to pass a temporary value (in this case, a temporary std::string implicitly converted from the const char *) to an argument of const-reference (in this case, const std::string &) type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top