In C++, if I write
token make_token() { return token{}; }
and then use it as follows
void use_token()
{
make_token();
// extra code
}
without assigning a token to a variable, token
's destructor fires before extra code executes. How can I get the destructor to only fire at the end of the function without having to make a variable?
Note: I want to completely avoid making a variable. I know I can do auto& t = make_token()
or similar, but I want to avoid precisely this by returning something (I don't know what) that doesn't have the destructor fired immediately.
Why I want this: basically, in my app (a compiler for a programming language) I have these things called tokens. A token's constructor can put a {
and indent, and its destructor can then put }
and un-indent. I thought it a good idea to set up functions which return these tokens by value, but I don't actually want to assign them to any value, since the tokens are useless and have no functions.
To alleviate confusion, my token
is not a lexical token. I use the work token
in lieu of the work cookie
. It's meant to do something in the constructor, wait until the end of its scope, and then do something in its destructor. That's it. By the way, if I was writing this in C#, I would write something like
using (make_token())
{
// my code here
}
and it would work as intended. But it turns out that something so simple is difficult in C++.
Yes. You can use a constant reference. This is called most important const in C++, and it's a feature that's not widely known.
Here's how you do it:
void use_token()
{
const token& myToken = make_token();
// now myToken is alive until the end of this function.
}
But you have to return strictly by value for this to work (you do that in the code you provided).
People who don't believe this, please try it yourself before attacking the post.