[clang] [clang] Infer lifetime_capture_by for STL containers (PR #117122)

Haojian Wu via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 22 01:40:29 PST 2024


================
@@ -268,6 +268,40 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
   }
 }
 
+static bool IsPointerLikeType(QualType QT) {
+  QT = QT.getNonReferenceType();
+  if (QT->isPointerType())
+    return true;
+  auto *RD = QT->getAsCXXRecordDecl();
+  if (!RD)
+    return false;
+  RD = RD->getCanonicalDecl();
+  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
+    RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
----------------
hokein wrote:

Thanks for the example. I think I understand what’s happening here.

The primary template Span is annotated with the gsl::Pointer attribute, so all its specializations should inherit this attribute.

However, in this example, at the point where we infer the `lifetime_capture_by` attribute for `vector`'s method, we don’t yet have a fully completed `ClassTemplateSpecializationDecl` for `Span<int>` (and therefore, no `PointerAttr`). This is likely because the instantiation of `Span<int>` isn’t required for the statement `std::vector<Span<int>> spans;`.

I think the following case would work without this special handling.
```
void use() {
  Span<int> abc({}); // trigger an instantiation of `Span<int>`.
  std::vector<Span<int>> spans;
  spans.push_back(std::vector<int>{1, 2, 3}); // warning.
}
```

I don’t have a better suggestion for addressing this issue directly. However, I think we should have a comment explaining it. (Should we do the same thing for the one in `CheckExprLifetime.cpp`?)


https://github.com/llvm/llvm-project/pull/117122


More information about the cfe-commits mailing list