I have the same question that was asked over here five years ago: Disallowing creation of the temporary objects
The reason I am asking it again is that I am specifically interested in C++11 and C++14 techniques for preventing the construction of temporaries.
One idea is to use "rvalue reference for *this":
class ScopedLock
{
public:
void enable() && = delete;
void enable() &
{
is_enabled = true;
}
~ScopedLock()
{
if (!is_enabled) {
std::cerr << "ScopedLock misuse." << std::endl;
std::terminate();
}
}
private:
bool is_enabled = false;
};
int main()
{
// OK
ScopedLock lock;
lock.enable();
// Compilation error.
ScopedLock().enable();
// std::terminate
ScopedLock();
// std::terminate
ScopedLock lock;
std::cout << "Y" << std::endl;
}
Perhaps there is a better way?