[cfe-dev] Question about lifetime bound annotation

Vitali Lovich via cfe-dev cfe-dev at lists.llvm.org
Mon May 24 12:24:52 PDT 2021


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?.

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.

Thanks,
Vitali
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20210524/31f1bb9b/attachment.html>


More information about the cfe-dev mailing list