In C++ is there a preferred way of dealing with a recursive function that reuses an unchanged object every time? For example (pseudo code):
void func(HashMap h, Logger logger, int depth)
{
// Do stuff then call func recursively...
func(h, logger, depth+1);
}
So every call we pass in several objects (hash map and logger) unchanged. Yes we can pass by reference but it still seems inefficient and doesn't look very pretty. The only alternative I can think of is global variables or bundling up the constant parameters in a struct.
What you're describing is a closed lexical environment, aka a "closure". That concept exists "for free" in dynamic languages like Lisp and Scheme, where the "let over lambda" pattern allows you to capture variables in a function and use them even though their enclosing scope is gone or exited.
You can simulate closures in C++ using a struct as the container for the captured variables and apply functions (functors) to the struct. The most common pattern for this is typically the way that operator() is used:
struct my_closure {
Hashmap &hmap_;
Logger &logger_;
int depth_;
my_closure(Hashmap &hmap, Logger &logger, int depth) :
hmap_(hmap), logger_(logger), depth_(depth)
{ }
void operator()(void)
{ /* do stuff here, including recurse */ }
};
The only thing this will save you is pushing extra stuff on the stack, which doesn't necessarily save you much in terms of cycles (1 struct reference [this pointer for the struct] vs. 2 references + 1 integer.) If your compiler supports tail recursion, this could be a benefit at the expense of readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With