https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106926

--- Comment #3 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to John Zwinck from comment #2)
> I agree the same problem could happen with std::string.  As for your idea to
> add an attribute, I assume you mean something like this:
> 
>     string_view(const char* s __attribute__((does_strlen)));

Yes.

> I think this would work but it seems like the attribute would have to be
> added in many places.

Why? I don't think there are that many places.

>  Instead, the compiler could statically determine that
> the length of the string is lost in code like this:
> 
>     string_view foo("bad\0string");

How would it determine that? By inlining the eventual call to strlen (several
function calls down from the location of the literal)?

> And maybe even here:
> 
>     const char* bar = "another\0one";
> 
> Though that may be a step too far because someone could hard-code the length
> 12 elsewhere, and there probably is code in the wild doing that.

I agree that's not a good idea.

> In general the diagnostic could apply wherever the compiler knows the
> contents will be copied.

But that doesn't apply to string_view, there's no copying. And such a warning
would require optimization and inlining to be effective. How would the compiler
know that? That's why I suggested an attribute, because the call site can give
a warning without having to know what happens inside the function, and
everything that it calls.

Relying on arbitrarily deep inlining doesn't sound like it will be very
effective, nor does expecting the compiler to just "know" which functions this
applies to.

>  Since that's not always possible to know, maybe it
> could assume copying will happen when the literal is passed to an
> out-of-line function.

That seems like a bad idea too. Every function is "an out of line function" at
-O0.

Reply via email to