Boost logo

Boost :

From: Rob Stewart (stewart_at_[hidden])
Date: 2002-08-22 14:08:18


From: =?Windows-1252?Q?Terje_Sletteb=F8?= <tslettebo_at_[hidden]>
> >From: "Terje Slettebø" <tslettebo_at_[hidden]>
>
> > But in what way would this be useful for lexical_cast?
> >
> > if you have std::string as target, you have something like:
> >
> > std::stringstream interpreter;
> > ...
> return std::string(interpreter.str());
>
> This uses in fact a specialisation. Without specialisation for
> std::basic_string as target, you'd have:
>
> std::string str;
>
> interpreter >> str;
>
> return str;
>
> The lexical_cast proposition doesn't use the specialisation above, maybe it
> should? I can't say I see it as completely evident that calling str(),
> followed by copy-construction, is faster than default-construction, followed
> by operator>>().

Take a look at the implementation of the istream functionality invoked by ">>".
I expect there is a great deal of overhead as compared to "interpreter.str()."
That is, unless it is specialized for stringstreams and strings.

What's more, given the code as written above, using swap() would be beneficial
as you can avoid copying the buffer contents once:

    std::string str;
    str.swap(interpreter.str());
    return str;

That approach avoids having to copy the contents of interpreter.str(), a
temporary, to str. Instead, the temporary's contents is handed over to str, and
vice versa. That's a clear win.

OTOH, the following would be just as efficient and is far simpler to boot:

    return interpreter.str();

-- 
Rob Stewart                           stewart_at_[hidden]
Software Engineer                     http://www.sig.com
Susquehanna International Group, LLP  using std::disclaimer;

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk