Search code examples
c++temporarytemporary-objects

prohibiting instantiation as a temporary object (C++)


I like using sentry classes in c++, but I seem to have a mental affliction that results in repeatedly writing bugs like the following:

{
  MySentryClass(arg);
  // ... other code
}

Needless to say, this fails because the sentry dies immediately after creation, rather than at the end of the scope, as intended. Is there some way to prevent MySentryClass from being instantiated as a temporary, so that the above code either fails to compile, or at least aborts with an error message at runtime?


Solution

  • I can't think of an automatic way to detect if you make this mistake or not. You could always create a macro that expands to the correct thing and use that to declare the sentry instead if you keep using it wrong.

    #define MY_SENTRY_CLASS(_X) MySentryClass _sentry(_X)
    

    and then use

    MY_SENTRY_CLASS(arg);
    

    or put a post-it on your monitor to remind you.