[format]: c_str() function

Would it be possible to add function c_str() into format interface? It would return const char/wchar_t* to internal string buffer. Use cases for such function: 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. 2. // class used to accept any string type struct parm_string { parm_string(const char* s) : str_(s) {} parm_string(const std::string& s) : str_(s.c_str()) {} const char* 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 /Pavel

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

"Samuel Krempp" <krempp@crans.ens-cachan.fr> wrote
but that's the problem : a temporary is still required... ... 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 ?
I see. With this info c_str() seems rather pointless. I was hit by using "f.str().c_str()" and got corrupted data, that was main motivation. Thanks for answer, /Pavel
participants (2)
-
Pavel Vozenilek
-
Samuel Krempp