I've a class like this:
class ScopedLock {
public:
ScopedLock (Locker *lock) { /*...*/ }
~ScopedLock () { /*...*/ }
};
Normally it's called like (this will call the constructor/destructor of ScopedLock at the correct place) :
{
ScopedLock l(&locker);
// ...
}
I've accidentally called it like:
{
ScopedLock(&locker);
// ...
}
What is the name for such a "thing"? Unused anonymous local variable?
Is there a possibility to prevent this? Is there a compiler warning available for such a "thing"?
You have created an unnamed temporary / nameless temporary object of type ScopedLock
that lives briefly and then dies at the ;
. The compiler does not issue a warning as it assumes you are doing something useful with it. It does not go into a ctor body to inspect if that might be the case. For example you want to create a temporary where your constructor might do some work:
ScopedLock() {
// do some work
}
You can't force a compiler to show a warning for such use-cases and there is no such flag in GCC.
The following SO posts can prove beneficial:
You can make a construction function marked as nodiscard
that should be invoked instead of constructor.
#include <iostream>
class ScopedLock final
{
private: ScopedLock(int, int) {std::cout << "constructed" << std::endl;}
private: ScopedLock(void) = delete;
private: ScopedLock(ScopedLock const &) = delete;
private: ScopedLock(ScopedLock &&) = delete;
private: ScopedLock & operator =(ScopedLock const &) = delete;
private: ScopedLock & operator =(ScopedLock &&) = delete;
public: [[nodiscard]] static ScopedLock
construct(int x, int y)
{
return ScopedLock{x, y};
}
};
int main()
{
ScopedLock(12, 123); // Error
ScopedLock::construct(12, 123); // Warning
auto lock(ScopedLock::construct(12, 123)); // Ok
}
online compiler
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With