[cfe-dev] Question about lifetime bound annotation
Richard Smith via cfe-dev
cfe-dev at lists.llvm.org
Mon May 24 15:21:28 PDT 2021
On Mon, 24 May 2021 at 12:25, Vitali Lovich via cfe-dev <
cfe-dev at lists.llvm.org> wrote:
> I was trying to incorporate the lifetime bound in an OSS project (
> https://github.com/capnproto/capnproto/pull/1246) and it surfaced a
> potential limitation of the annotation (or perhaps I'm just not utilizing
> its full power yet).
>
> Is there a way to use the lifetime annotation to have the compiler track
> the lifetime through copies? For example, if std::string's conversion
> operator to std::string_view is annotated, will copying/moving/assigning
> the returned std::string_view (e.g. when building up a vector of
> string_view in a loop but accidentally having that string_view point to a
> string local to the loop) cause the compiler to still see the copies as
> having their lifetimes tied to the original std::string? One would think
> that defaulted copies/moves/assignments would automatically preserve the
> lifetime & there would need to be some kind of additional annotation for
> the more complex use-cases, but from my testing this is perhaps not yet
> implemented?.
>
Yes, this should work as you describe, but that is not implemented yet.
> Relatedly, it seems even as something as simple as below didn't trigger
> the warning so I'm wondering if I'm misusing it or if the lifetime tracking
> is just very limited in the cases it can find.
>
> struct Foo {
> std::string buf;
> operator std::string_view() const [[clang::lifetimebound]] {
> return buf;
> }
> };
>
> int main() {
> for (int i = 0; i < 5; i++) {
> std::string_view x;
> {
> Foo str = { .buf = std::to_string(i) };
> x = str;
> }
> std::cerr << x << "\n";
> }
> }
>
> clang++ -std=c++20 -Wall doesn't seem to generate a warning (v13 from
> revision 0e92cbd6a652c). Adding -fsanitize=address does cause the program
> to crash when run.
>
At the moment, the lifetimebound warning only considers initializations,
not assignments. We could in principle warn that `x = str;` assigns a value
with shorter lifetime to a variable with longer lifetime, though that would
have false positives on cases like:
string_view x;
{
Foo str = ...
x = str;
...
x = "something else";
}
... or if x is not used after the lifetime of str ends. Correctly handling
those cases would require a more sophisticated kind of analysis than the
syntactic check we currently perform. (Though perhaps the simplistic
analysis that warns directly on the `x = str;` assignment without
considering the context would be useful enough in practice, despite the
potential for false positives?)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20210524/6c18b60c/attachment.html>
More information about the cfe-dev
mailing list