Connecting Tech Pros Worldwide Forums | Help | Site Map

STL string class

mike7411@gmail.com
Guest
 
Posts: n/a
#1: Apr 21 '07
When you use she STL string class and the c_str() function, how does
the memory returned by c_str() get allocated and destroyed?

Thank you.


Mark P
Guest
 
Posts: n/a
#2: Apr 21 '07

re: STL string class


mike7411@gmail.com wrote:
Quote:
When you use she STL string class and the c_str() function, how does
the memory returned by c_str() get allocated and destroyed?
>
Thank you.
>
The memory is controlled by the string object-- after the string is
destructed you must not access the memory returned by c_str().
Ivan Vecerina
Guest
 
Posts: n/a
#3: Apr 21 '07

re: STL string class


"Mark P" <usenet@fall2005REMOVE.fastmailCAPS.fmwrote in message
news:cBcWh.1109$ns5.542@newssvr17.news.prodigy.net ...
: mike7411@gmail.com wrote:
: When you use she STL string class and the c_str() function, how does
: the memory returned by c_str() get allocated and destroyed?
: >
: Thank you.
: >
:
: The memory is controlled by the string object
Yep.

: after the string is destructed
: you must not access the memory returned by c_str().

Not only destruction, but any operation that modifies
the string may invalidate the memory that was returned
by c_str().
I.e.:
std::string s = "Hello";
char const* p = s.c_str();
std::cout << p << std::endl; //ok
s.append('.');
std::cout << p << std::endl; // UNDEFINED BEHAVIOR


hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

James Kanze
Guest
 
Posts: n/a
#4: Apr 21 '07

re: STL string class


On Apr 21, 4:57 am, "Ivan Vecerina"
<_INVALID_use_webfo...@ivan.vecerina.comwrote:
Quote:
"Mark P" <use...@fall2005REMOVE.fastmailCAPS.fmwrote in message
Quote:
news:cBcWh.1109$ns5.542@newssvr17.news.prodigy.net ...: mike7...@gmail.comwrote:
Quote:
: When you use she STL string class and the c_str() function, how does
: the memory returned by c_str() get allocated and destroyed?
Quote:
: The memory is controlled by the string object
Yep.
Quote:
: after the string is destructed
: you must not access the memory returned by c_str().
Quote:
Not only destruction, but any operation that modifies
Any operation which permits modification, in fact. Calling [],
at(), begin() or end() on a non-const string, or through a
non-const reference to the string, may also invalidate the
pointer.

--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Closed Thread