Boost logo

Boost :

Subject: Re: [boost] Heads up - string_ref landing
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2012-11-27 02:05:48


On Tue, Nov 27, 2012 at 10:56 AM, Yanchenko Maxim
<maximyanchenko_at_[hidden]> wrote:
>
>
> 27.11.12, 13:51, "Jeffrey Lee Hellrung, Jr." <jeffrey.hellrung_at_[hidden]>":
>>
>> On Mon, Nov 26, 2012 at 7:03 PM, Yanchenko Maxim
>> <maximyanchenko_at_[hidden]>wrote:
>> > Hi Daniel, I'm fully with you here. The construction of string_ref should
>> > be explicit (except maybe literals if we can detect them in compile time)
>> > as we're giving away pointers to something that is externally managed.
>> > Look at std::string::c_str/data, any smart_ptr::get etc - everything is
>> > explicit for a reason. Implicit conversions to pointers are very dangerous
>> > here.
>> > No containers give away their internals implicitly, and this is Good Thing.
>> >
>> > Consider a vector of pointers, for example. You don't want to implicitly
>> > put a pointer managed by a smart pointer there, you want it to be explicit
>> > so it's visible and you don't forget putting reset/release near a
>> > push_back. Same applies to a vector of string_ref - you want to be sure
>> > that the string referred by it lives as long a needed, and there is no
>> > other way except explicit construction.
>> >
>>
>> I was under the impression that string_ref's proposed purpose was to
>> provide a generic concrete (i.e., non-template) interface for string
>> algorithms (both as parameters and results), and for this purpose, the
>> above arguments seem irrelevant. The lifetime concerns are no worse than
>> for a std::string const &.
>
> Should we ban vector<string_ref> then?
> Otherwise it's error-prone:
>
> vector<string_ref> v;
> std::string s;
> v.push_back(s);
>
> Containers of string_ref are very useful while working with external textual data, e.g. parsing - to store various chunks of parsed text like identifiers. But if you want to add some predefined identifiers from other sources like std::string - you want the compiler to warn you if you're going to do something dangerous. Explicit construction is very useful and saves from leaks and ownership errors.
> This is from my team's real experience with our string_ref-like class.

I think, banning is an overstatement. Caution must be exercised, true.
Just as much caution as with the following code:

vector<pair<const char*, size_t> > v;
std::string s;
v.push_back(make_pair(s.c_str(), s.size()));

I admit it's more explicit, but nevertheless the string_ref variant is
still valid.


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