Hacker News new | ask | show | jobs
by pfultz2 2616 days ago
Clang's lifetime profile will catch the first example:

    <source>:8:16: warning: passing a dangling pointer as argument [-Wlifetime]
      std::cout << sv;
                   ^

    <source>:7:38: note: temporary was destroyed at the end of the full expression
      std::string_view sv = s + "World\n";
                                         ^
And cppcheck will catch the second example:

    <source>:7:12: warning: Returning lambda that captures local variable 'x' that will be invalid when returning. [returnDanglingLifetime]
        return [&]() { return *x; };
               ^
    <source>:7:28: note: Lambda captures variable by reference here.
        return [&]() { return *x; };
                               ^
    <source>:6:49: note: Variable created here.
    std::function<int(void)> f(std::shared_ptr<int> x) {
                                                    ^
    <source>:7:12: note: Returning lambda that captures local variable 'x' that will be invalid when returning.
        return [&]() { return *x; };
               ^
Cppcheck could probably catch all the examples, but it needs to be updated to understand the newer classes in C++.
1 comments

For everyone interested in experimenting with this: https://gcc.godbolt.org/z/vmcnXh

Godbolt's compiler explorer is a great tool to try new features (language, compiler, standard library, etc.).