Boost logo

Boost :

Subject: Re: [boost] Boost.Convert+Boost.Parameter
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2009-03-03 18:17:50

On Tue, Mar 3, 2009 at 2:15 PM, Steven Watanabe <watanabesj_at_[hidden]> wrote:
> Emil Dotchevski wrote:
>> On Tue, Mar 3, 2009 at 1:26 PM, Steven Watanabe <watanabesj_at_[hidden]>
>> wrote:
>>> Emil Dotchevski wrote:
>>>> 2) convert<std::string> necessarily returns std::string (I think it's
>>>> important user-defined conversions to have the freedom to return char
>>>> const *. Many interfaces that take strings are commonly overloaded for
>>>> std::string and char const * for efficiency reasons.)
>>> How common is this going to be in reality?  Won't returning
>>> const char* usually introduce problems with memory management?
>> I think that whether this is common or not is not important, my point
>> is that it is a valuable optimization technique.
> I don't think it is.  It's too fragile.  Functions
> taking const char* arguments don't have the same problems.

Functions that take char const * arguments are the reason why it's
important to allow for to-string conversions to return char const *.

>> If conversion of objects of type foo to string is for some reason
>> critical for performance, you can have foo contain a std::string and
>> make its to-string overload return a char const *, through
>> std::string::c_str().
> which will work fine, until some generic code converts a temporary
> to a string.

What you probably mean is that if to_string returns char const *, the
following would be undefined:

char const * to_string( foo const & );
foo bar();
char const * s=to_string(bar()); //oops

That's true, however this other scenario, where the foo object is also
temporary, is valid:

char const * to_string( foo const & );
foo bar();
void print( char const * );
void print( std::string const & );

So yes, it's tricky but it is still a valid optimization technique,
IMO. We can specify to_string accordingly, saying that the returned
object is only valid for the lifetime of the object being converted to
string so the caller would know to do std::string s=to_string(bar())
which would be fine always.

By the way, returning std::string doesn't guard against such errors:

std::string to_string( foo const & );
foo bar();
char const * s=to_string(bar()).c_str(); //oops.

Emil Dotchevski
Reverge Studios, Inc.

Boost list run by bdawes at, gregod at, cpdaniel at, john at