I have an object on the stack that requires another object for it's constructor, like this:
{
ObjectDef def(importantData); // should die as soon as obj is created
def.setOptionalData(100);
Object obj(def); // should live for the remainder of the function body
}
Ideally, I like to put variables like def
in their own scope. This gives me the name "def" back, and makes it clear that it isn't useful anymore.
For example, what happens here with result
I would like to do with obj
:
// scope block
{
int result = complexFunction() + anotherFunction();
printf("the result is %i", result);
doMoreThingsWithIt(result);
}
// "result" is now gone
The problem though, is that there is no way to do that here, that I can see. The constructor of Object obj
cannot be before the scope because it's constructor needs def
, and it cannot be within the scope because obj
needs to survive much longer than def
.
Is there anyway to accomplish limiting def
's scope to be shorter than obj
, or should I just accept that it has to stay in scope for at least as long?
You could use a lambda:
Object obj{[&]{ ObjectDef def{importantData}; def.setOptionalData(100); return def; }()};
If ObjectDef
frequently needs it's optional data set and this is a common pattern, consider adding a constructor to ObjectDef
that allows optional data to be set or creating a named helper function that does the job the lambda does here.