1

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.

obamator
  • 478
  • 3
  • 13
  • 1
    If getLock returns a class, which unlocks on destruction : it will not prevent non-assignment call as you wish, but it will prevent locked lock – galinette Apr 06 '15 at 13:00
  • 1
    clang and gcc have a warning for that (using the returned value of function). (see http://stackoverflow.com/questions/2870529/g-how-to-get-warning-on-ignoring-function-return-value) – Jarod42 Apr 06 '15 at 13:01
  • @Jarod42 : but you will generally have tons of warnings in that case, no? A lot of functions use optional return values (such as stream operators, etc...) – galinette Apr 06 '15 at 13:03
  • @galinette: the warning works with attribute, so only the specified functions provoke the warning. – Jarod42 Apr 06 '15 at 13:05

1 Answers1

1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523