By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,953 Members | 1,611 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,953 IT Pros & Developers. It's quick & easy.

What storage does std::string::c_str() use?

P: n/a
All,

If I am not mistaken I had some problems with code like this:

std::string foo, bar;
....
somefunc( foo.c_str(), bar.c_str() );

Problem was that c_str() used buffer shared btw instances of
std::string in that implementation. I did not find anything that
standart would explicitly say about this case. So what would you say?

Thanks,
Slava
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Vyacheslav Kononenko wrote:
If I am not mistaken I had some problems with code like this:

std::string foo, bar;
...
somefunc( foo.c_str(), bar.c_str() );
What kind of problems? The standard says you cannot rely on those
pointers if you call any non-const member functions for the strings
after obtaining the pointers.
Problem was that c_str() used buffer shared btw instances of
std::string in that implementation. I did not find anything that
standart would explicitly say about this case. So what would you say?


I'd say, you had a terribly buggy implementation.

Victor
Jul 22 '05 #2

P: n/a
vy********@kononenko.net (Vyacheslav Kononenko) wrote:
All,

If I am not mistaken I had some problems with code like this:

std::string foo, bar;
...
somefunc( foo.c_str(), bar.c_str() );

Problem was that c_str() used buffer shared btw instances of
std::string in that implementation. I did not find anything that
standart would explicitly say about this case. So what would you say?


If foo and bar contain the same string, then you could get the
same buffer, eg:
foo = bar = "hello";
then ( foo.c_str() == bar.c_str() ) is possible.

When writing 'somefunc' you should allow for this possibility.

Also if the strings overlap you could (conceivably -- I don't
know of any implementation that actually does this) get the
same buffer:
foo = "rhombus";
bar = "bus";
then ( foo.c_str() + 4 == bar.c_str() ) could possibly be true.

However the standard requires that the result of c_str() is
valid for a certain time, so if the strings are different and
you get the same buffer, your implementation is broken.
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.