Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does std::string manages this trick?

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?

like image 889
lurscher Avatar asked Jan 25 '12 16:01

lurscher


People also ask

What does std::string () do?

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.

Is std::string allocated on the heap?

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.

Why do I need std::string?

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.

What does std::string end () return?

Returns an iterator to the character following the last character of the string.


1 Answers

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");
like image 115
JaredPar Avatar answered Sep 28 '22 15:09

JaredPar