Reputation: 468
Is it possible to declare a function in such a way that
auto i = foo.GetLock();
works, but
foo.GetLock();
causes a compile error?
My interface has a method that returns RIIA-style lock object and I want to make sure nobody decides just calling GetLock() locks the lock.
It used to be something like this
class CSomethingOrElse : private CLockable
{
...
} foo;
CLocker<CSomethingOrElse> lock(foo);
but it's too verbose for my taste and I would really like to make use of auto
.
Upvotes: 1
Views: 61
Reputation: 726809
foo.GetLock();
is an expression statement, so any valid expression can be used in that way. You cannot prohibit that at compile time: the best you can get is a warning.
Assuming that your object releases the lock on destruction, the call that does not store the result in a variable shouldn't be a big problem, because the lock would be acquired and released right away.
Creating a guard object, similar to what you describe in your solution, is the proper way to go. In fact, the Standard Library of C++ does it in a similar way with std::lock_guard
.
Upvotes: 1