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?
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
The string object itself is stored on the stack but it points to memory that is on the heap. Why? The language is defined such that the string object is stored on the stack. string's implementation to construct an object uses memory on the heap.
Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did. Save this answer.
Returns an iterator to the character following the last character of the string.
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");
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