Jul 13, 2025

[C++][Rust] default Lifetime annotation from Rust

  1. The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference. In other words, a function with one parameter gets one lifetime parameter: fn foo<'a>(x: &'a i32); a function with two parameters gets two separate lifetime parameters: fn foo<'a, 'b>(x: &'a i32, y: &'b i32); and so on.
  2. The second rule is that, if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: fn foo<'a>(x: &'a i32) -> &'a i32.
  3. The third rule is that, if there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.

Consider the idea and apply to C++ with 
gnu::lifetimebound
#include <map>
#include <string>

using namespace std::literals;

// Returns m[key] if key is present, or default_value if not.
template<typename T, typename U>
const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
                        const T &key, /* note, not lifetimebound */
                        const U &default_value [[clang::lifetimebound]]) {
  if (auto iter = m.find(key); iter != m.end()) return iter->second;
  else return default_value;
}

int main() {
  std::map<std::string, std::string> m;
  // warning: temporary bound to local reference 'val1' will be destroyed
  // at the end of the full-expression
  const std::string &val1 = get_or_default(m, "foo"s, "bar"s);

  // No warning in this case.
  std::string def_val = "bar"s;
  const std::string &val2 = get_or_default(m, "foo"s, def_val);

  return 0;
} 
Output:
<source>:19:55: warning: temporary bound to local reference 'val1' will be destroyed at the end of the full-expression [-Wdangling]
   19 |   const std::string &val1 = get_or_default(m, "foo"s, "bar"s);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.