Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
SuperElectric Avatar asked Jan 03 '11 22:01

SuperElectric


People also ask

Is always used when the compiler has to create a temporary object?

Temporary objects are often created during execution of a C++ program. Result of C++ operators (unary, binary, logical, etc.) and return-by-value functions always give rise to temporary objects. For built-in types, the cost of creating temporaries is minimal because compilers often use CPU registers to manipulate them.

What are temporary objects?

A temporary object is an unnamed object created by the compiler to store a temporary value.

What is a temporary Cpp?

In C++ temporaries are unnamed objects that compiler creates in various contexts. The typical uses include reference initialization, argument passing, evaluation of expressions (including standard type conversions), function returns, and exceptions (throw expressions).


1 Answers

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.

like image 139
Roger Perkins Avatar answered Nov 15 '22 18:11

Roger Perkins