|
Boost : |
From: Phil Endecott (spam_from_boost_dev_at_[hidden])
Date: 2021-10-15 12:14:14
Dominique Devienne wrote:
> On Thu, Oct 14, 2021 at 2:04 PM Phil Endecott via Boost <
> boost_at_[hidden]> wrote:
>
>> >> auto url = parse_url(str);
>> >>
>> >> The problem is that url is a view of the string parameter, but
>> >> nothing warns the user about that and...
>> >
>> > Well, it is documented profusely. I agree there is some danger here
>> > but with great danger comes great power. Or something about
>> great responsibility?
>>
>> I don't think this is acceptable. What do others think?
>
>
> I don't mind. It's no different than std::string and std::string_view.
Exactly, it's like returning a string_view from a function - which
you should never do, at least not without an obvious indication...
> Maybe having parse_url_as_view(str) and a safer parse_url(str) using
> the former but not returning a view would satisfy you?
Yes, that's exactly what I suggested.
The alternative is to try to find some way to return something that
can't be assigned to auto. This may be possible with something like
a private_url_view class that wraps a view and makes everything private:
url u = parse_url(s);
// parse_url() returns a private_url_view, url is constructable from private_view
url_view v = parse_url(s);
// parse_url() returns a private_url_view, url_view is constructable from private_view
auto u = parse_url(s);
// Can we make that fail to compile by making private_url_view's ctors private?
// If not...
auto p = u.path();
// ...we can prevent the user from using it for anything by hiding all of
// its methods.
// But:
url u2 = u;
func(u);
// We need to prevent those too. I think we can prevent assigning from
// a private_view to a url[_view] by qualifying url[_view]'s assignment
// and copy ctor with &&:
url::operator=(const private_url_view& v) = delete;
url::operator=(private_url_view&&) { ... }
I'm sure that smarter people than me already know the correct pattern for
doing this. Searching I found p0672r0 which addresses how to fix the
similar issues for proxy types and expression templates but doesn't mention
views.
I also found blog posts by Arthur O'Dwyer talking about string_view, e.g.
https://quuxplusone.github.io/blog/2018/03/27/string-view-is-a-borrow-type/
Quote:
A function may have a borrow type as its return type, but if so, the
function must be explicitly annotated as returning a potentially dangling
reference. That is, the programmer must explicitly acknowledge responsibility
for the annotated functionâs correctness.
Regardless, if f is a function so annotated, the result of f must not
be stored into any named variable except a function parameter or for-loop
control variable. For example, auto x = f() must still be diagnosed as a
violation.
Regards, Phil.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk