Alex Rivera | Logout

prohibiting instantiation as a temporary object (C++)

Asked 2011-01-03T22:26:31.597
10

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?

Edit
Report

2 Answers

8

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.

answered 2011-01-03T22:40:00.463
4

The only thing you could do is make the constructors private and force access through a helper function. This is far less similar than the initial construction syntax and less likely to be mistaken. You could also allocate on the heap (still a waste) but it's much easier to spot. However, if you want your class to be constructible, you can't stop people constructing rvalues of that type.

Edit: IF you know that MySentryClass always takes an argument, you could disallow construction AND and only allow operator=(arguments). This would force you to do

MySentryClass x;
x = arg;

You could do some kind of method chain for it.

MySentryClass x;
x.SetArg1(arg).SetArg2(arg2).construct();
answered 2011-01-03T22:32:20.107

Your Answer