It doesn't look any weirder than a call to a void function named Lock
.
Not that I'm suggesting that you go around thinking of functions as just funny-named constructors (of whatever their return type is), but the syntax is intentionally similar.
I can't for the moment think of a good reason to create but not use a Lock
, but:
LockSession(lock);
has the same side-effects as you'd expect from:
acquire_and_then_immediately_release(lock);
As you say, this is very rarely what you want, so it might well look to the casual reader like an error. If for some odd reason it is what you want, and you want to avoid confusing people, you can do:
{
LockSession session(lock);
// release immediately
}
or for that matter:
void acquire_and_then_immediately_release(Lock &lock) {
LockSession(lock);
}
with the same effect and less chance of head-scratching whether that's really what you meant, or whether you've just made the common mistake of forgetting to supply a name and hence holding the lock for less time than you should.
Why would you want to acquire and then immediately release a lock? Probably because you're (ab)using it as a slightly peculiar semaphore. For example you could create a bunch of threads with a lock held, and if the first thing each thread does is this, then none of them will get past it until all the thread creation is done (plus anything else the parent wants the threads to be able to see) and the parent releases the lock. There are probably better examples out there of objects whose construction side-effects are significant.
Moving away from side-effects, another possibility is that if you want to check that a string is valid XML, you could write:
xml::dom::Document(mystring);
expecting an exception for invalid data. Again, the code would be more readable if you called a well-named function that does it. And constructing a DOM tree is not the most efficient way to validate XML. But if a class is what you already have then using it is the simplest thing that works.
I suppose the issue is that the name of a class is rarely descriptive of the side-effects of creating and destroying it. So a lone temporary will tend to look weird for that reason.