From: James Kanze US/ESC 60/3/141 #40763
Subject: Re: allocator and GC locality (was Re: cost of malloc)
Date: 
Message-ID: <KANZE.95Aug21155322@slsvhdt.lts.sel.alcatel.de>
In article <··········@info.epfl.ch> "Stefan Monnier"
<··············@epfl.ch> writes:

|> In article <···················@slsvhdt.lts.sel.alcatel.de>,
|> James Kanze US/ESC 60/3/141 #40763 <·····@lts.sel.alcatel.de> wrote:
|> ] 	extern "C" void     f( char const* s ) ;
|> ] 	string              s ;
|> ] 
|> ] 	f( s.c_str() ) ;
|> ] 
|> ] It's hardly likely that `f' will free it (since in other contexts, `f'
|> ] will be called with e.g.: a string literal), and you don't want to
|> ] hassle having to maintain a pointer yourself.

|> Tell me: how do you do it currently in C ?
|> Don't you have to maintain the pointer yourself ?

There are several solutions in C, all of them problematic.  (The most
frequent seems to be to return a pointer to static memory.)

|> Tell me exactly how "f(s.c_str())" can be correct !
|> c_str has to return a char*, which can either be dynamically allocated or
|> stack-allocated. Stack allocation is incorrect in this case and if you prefer
|> dynamic allocation, then c_str cannot free the char*, it must be f(). So if f()
|> doesn't free the char*, the expression is necessarily wrong !

The pointer returned by c_str belongs to s (the string), and will be
freed when s goes out of scope.

|> The only alternative I can see to what I suggested is for c_str to use a
|> pre-allocated char array which is passed to it as a parameter !

|> ] In the case of the standard string class, it is already documented
|> ] when the pointer returned by c_str becomes invalid.  So you know
|> ] exactly when you can free it.  (If memory serves me right, it is until
|> ] the next non-const function is called on the string, or the
|> ] destructor.)

|> How does this work ? Does it redefine operations on "char*" ?

No, c_str returns a pointer which still belongs to the string, as
explained above.

In the implementations I'm familiar with, the returned pointer is to
the actual internal representation of the string; change the string,
and the pointer is liable to change too.  (This is allowed, but not
required, by the standard.)
-- 
James Kanze         Tel.: (+33) 88 14 49 00        email: ·····@gabi-soft.fr
GABI Software, Sarl., 8 rue des Francs-Bourgeois, F-67000 Strasbourg, France
Conseils en informatique industrielle --
                              -- Beratung in industrieller Datenverarbeitung