<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++.Godbolt's compiler explorer is a great tool to try new features (language, compiler, standard library, etc.).
But there is an alternative/complementary approach, which is to simply avoid potentially unsafe C++ elements, like pointers/references, arrays, std::string_views, std::threads, etc., substituting them with safe, largely compatible replacements[2]. This approach has the benefit that an associated safety-enforcing "linter" would not impose the same kinds of "severe" usage restrictions that the lifetime profile checker (or, say, the Rust compiler) does.
[1] https://devblogs.microsoft.com/cppblog/lifetime-profile-upda...
[2] https://github.com/duneroadrunner/SaferCPlusPlus
edit: grammar
There isn’t really any useful safe subset of C++. If there were, Rust may never have been created in the first place.
C++ still does not have an absolutely safe subset, but it has a safe-enough subset, and plenty of other merits that will ensure its continued competitiveness.
Rust will continue improving, too, and someday may be as expressive as C++ is today, or perhaps even as expressive as C++ is then. That will be a good day, although by then some other language will be on the rise, its users hoping to displace C++ and, given enough luck and hard work, Rust.
V could be interesting.
Until Rust's tooling catches up with C++/CLI, C++/CX, C++/WinRT + .NET or Java + C++ (Eclipse/Netbeans/Oracle Studio), CUDA, Unreal/Unity, GLSL/HLSL/Metal Shaders allow for, it will stay as a safe way to write CLI apps and a couple of UNIX libs.
I like the language and advocate it often, but I am also very pragmatic regarding the areas I and customers work on.