Subject: Re: [boost] Heads up - string_ref landing
From: Yanchenko Maxim (maximyanchenko_at_[hidden])
Date: 2012-11-16 12:18:23
16.11.2012, 19:30, "Marshall Clow" <mclow.lists_at_[hidden]>:
> And for most cases, the code internal to "f" and "g" won't care that they got a string_ref instead of a const std::string.
In many, not most, and definitely not all.
Here is an example I gave to Olaf:
v.push_back( "foo" ); // OK - lifetime of string literal is infinite
v.push_back( std::string("bar") ); // BOOM
std::string s = "foobar";
v.push_back(s); // BOOM
When it comes to ownership, explicit is better than implicit.
Every time you want to store a char_range for future use, you want to be 100% sure that everything it's pointing at will live longer than char_range.
How can you enforce it if everything is implicit? Forget about help from compiler, you won't even see the places of such ownership leaks!
Making char_range ctor explicit makes a programmer to think twice: "OK, here I'm converting this string to a char_range - is it supposed to live longer than my string? Will my string live long enough and *unchanged* (no resize/reallocation)?"
char_range is an optimization tool, and when used with std::string it causes its abstraction to leak as it utilizes the hidden knowledge that the source std::string
1) will live longer than char_range
2) won't resize/realloc its internal buffer as the char_range points directly into it
It's essentially a naked pointer into volatile memory and should be used with the same level of (pre)caution (and better not used at all until you need to optimize speed - otherwise just good old *safe* copies of std::string should be used by default).
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk