If temp
is unused, in essence it is also probably not needed. Remove it.
#include <cstdio>
int f() { return 5; }
int main() {
if(f()) {
printf("hello!\n");
}
return 0;
}
I realise this is an MCVE, so why would it need to be there in the first place?
As you mention in the comments, the destructor of temp
is important in the target code. Adding an additional set of braces will add both control of the lifetime of the temporary and ensure its use (hence remove the warning);
#include <iostream>
using namespace std;
struct A {
~A() { cout << "~A()" << endl; }
explicit operator bool() const { return true; }
};
A f() { return A{}; }
int main() {
{ // braced to limit scope...
auto&& a = f(); // can be const A&
if ( a ) {
cout << "hello!" << endl;
}
} // braced to limit scope....
return 0;
}
Demo code.
Given the additional constraints of the lifetime of temp
been extended to the end of an associated else
, simply forcing the warning to be silenced will work (compiler limited).
if (const int &temp __attribute__((unused)) = f())
C++11 brings with it the [[...]]
style of attributes, but the unused
is not standard, but clang does support this syntax [[gnu::unused]]