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

  • Thread starter Vyacheslav Kononenko
  • Start date
V

Vyacheslav Kononenko

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
 
V

Victor Bazarov

Vyacheslav said:
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
 
O

Old Wolf

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.
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top