mardi 2 mai 2023

Returning a temporary argument in C++: Identity function

In C++, I can write a statement std::string& x = f();. If f() returns a std::string (not a reference), it will extend the lifespan of the temporary variable until x goes out of scope.

What if I wanted to write something like std::string& x = identity(f());, where identity should "pass through" the value. Is there a way to do so which can extend the lifespan of the temporary value returned by f() just like it did in the simpler case?

I'm willing to overload identity as needed to support the different kinds of references if needed, but the rules for lifespan extension were always tricky, so I'm not sure if it can be done.

Aucun commentaire:

Enregistrer un commentaire