char *std::string::c_str() const. How is it possible to work?

G

grishin

Good morning,

cplusplus.com says:
"const char* c_str ( ) const;

Get C string equivalent
Generates a null-terminated sequence of characters (c-string) with the
same content as the string object and returns it as a pointer to an
array of characters."

I'm just wondering where does it allocate space and then store the
pointer?
It's a const member so it's not allowed to modify any member then.

"The values in this array are only granted to remain unchanged until
the next call to a non-constant member function of the string object."

For me it says that main string class's storage and c_str's storage
are different storages then.

Some technique I don't know yet.

Thank you.
Yuriy Grishin.
 
G

gwowen

For me it says that main string class's storage and c_str's storage
are different storages then.

No, it does not says this. Typically, whenever the std::string stores
its content in a char array, it'll merely return the address of the
beginning. The valid-lifetime guarantee allows this to happen, along
with the fact that it returns a const pointer. Whether this does
actually happen is an implementation issue.
Some technique I don't know yet.

There are other ways certainly other ways, that probably get used in
some more-or-less esoteric implementations. c_str() is allowed to
throw, so one could imagine some other memory allocation procedure (a
hidden delete[]()/new[]()). I'd imagine 99.9% of implementations use
the trivial one, though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top