Skip to content

Investigate adding lifetimebound attributes to important functions #3754

Description

The [[clang::lifetimebound]] and [[msvc::lifetimebound]] attributes can detect dangerous usage:

C:\Temp>type woof.cpp
struct X {
    int a;
};

#ifdef __clang__
#define ATTR [[clang::lifetimebound]]
#else
#define ATTR [[msvc::lifetimebound]] // should use _HAS_MSVC_ATTRIBUTE
#endif

const int& f(const X& x ATTR) noexcept {
    return x.a;
}

int main() {
    const int& r = f(X{1729}); // dangerous, emits warning
    (void) r;
}
C:\Temp>clang-cl /EHsc /nologo /W4 /MTd /Od /c woof.cpp
woof.cpp(16,22): warning: temporary bound to local reference 'r' will be destroyed at the end of the full-expression
      [-Wdangling]
    const int& r = f(X{1729}); // dangerous, emits warning
                     ^~~~~~~
1 warning generated.

C:\Temp>set esp.extensions=cppcorecheck.dll

C:\Temp>cl /EHsc /nologo /W4 /MTd /Od /c /analyze:autolog- /analyze:plugin espxengine.dll woof.cpp
woof.cpp
C:\Temp\woof.cpp(16) : warning C26815: The pointer is dangling because it points at a temporary instance which was destroyed.

We should investigate adding these attributes to important functions in the STL.

To avoid regressions, we should:

  • Have an escape hatch
  • Do this gradually
  • Have test coverage (similar to our "include all headers" tests) that verifies that the STL itself is clean with respect this these dangling-reference warnings
  • For each added attribute, manually verify that it detects bogus usage

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSomething can be improved

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions