Boost logo

Boost :

From: Samuel Krempp (krempp_at_[hidden])
Date: 2004-02-23 13:25:45


On Mon, 2004-02-23 at 18:15, Pavel Vozenilek wrote:
> 1.
> void foo(const char*) { ...}
>
> format f("...")
> f % ...
> foo(f.c_str());
>
> This is shorter and faster than
> foo(f.str().c_str());
>
> No temporary gets created.

but that's the problem : a temporary is still required (because a format
object does not store the final string in a contiguous way, only
std::string pieces that are concatenated together when calling str() )
So moving the temporary handling issue inside boost::format would not
bring much, except syntactic sugar, with the price of possible issues
caused by the hidden temporary. though any user of a "c_str()" function
should expect a temporary object semantic, like std::string's c_str()

Now, why store the string pieces rather than the final string ? because
the way arguments are formatted one by one, we need to have all the
pieces anyway, making the final string has to be done by concatenation.
Format could keep a copy of the concatenated result, but that's not its
primary job (which is formatting arguments, and/or storing handling
format parameters, not caching formatted results).

> parm_string(const char* s) : str_(s) {}
> parm_string(const std::string& s) : str_(s.c_str()) {}
> void foo(parm_string) { ... }
>
> format f("...")
> f % ...
> // ERROR - pointer to deleted temporary gets used inside foo()
> foo(f.str());
> foo(f.c_str()); // would be OK

yes, I see the issue.
But I'm not convinced factoring the temporary handling into format is
the best solution.

Can you send me more details on your usage example ? Why not store
std::string fconcat = str(f);
and then use it rather than f, to simply and clearly decouples temporary
/ c-string aspects from the formatting action ?

regards,

-- 
Samuel

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