Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent unused variable warning with non trivial destructor

When I rely on lifetime extension to assign to a class with a non trivial destructor the compiler (both gcc and clang) issue unused variable warnings. Is there anyway to get around this? https://wandbox.org/permlink/qURr4oliu90xJpqr

#include <iostream>

using std::cout;
using std::endl;

class Something {
public:
    explicit Something(int a_in) : a{a_in} {}

    Something() = delete;
    Something(Something&&) = delete;
    Something(const Something&) = delete;
    Something& operator=(Something&&) = delete;
    Something& operator=(const Something&) = delete;

    ~Something() {
        cout << this->a << endl;
    }

private:
    int a;
};

int main() {
    const auto& something = Something{1};
    return 0;
}

Note that when I switch to not relying on lifetime extension, things work just fine https://wandbox.org/permlink/cJFwUDdi1YUEWllq

I even tried manually defining all the constructors and then deleting them with a templated static_assert so that it only fires when those constructors are called https://wandbox.org/permlink/fjHJRKG9YW6VGOFb

#include <iostream>

using std::cout;
using std::endl;

template <typename Type>
constexpr auto definitely_false = false;

template <typename T = void>
class Something {
public:
    explicit Something(int a_in) : a{a_in} {}

    Something() { static_assert(definitely_false<T>, ""); }
    Something(Something&&) { static_assert(definitely_false<T>, ""); }
    Something(const Something&) { static_assert(definitely_false<T>, ""); }
    Something& operator=(Something&&) { static_assert(definitely_false<T>, ""); }
    Something& operator=(const Something&) { static_assert(definitely_false<T>, ""); }

    ~Something() {
        cout << this->a << endl;
    }

private:
    int a;
};

int main() {
    const auto& something = Something<>{1};
    return 0;
}

Let's say just for the language lawyer tag's sake that casting to void is not an option. Can I do something with the constructors/destructors that will help silence this warning?

like image 264
Curious Avatar asked Nov 13 '17 06:11

Curious


2 Answers

Not the exact answer you are looking for, but here is a workaround suggestion:

Pre C++17

Use std::ignore like this:

const auto& something = Something{1};
std::ignore = something;

Post C++17

Use the maybe_unused attibute, like this:

[[maybe_unused]] const auto& something = Something{1};
like image 176
gsamaras Avatar answered Nov 10 '22 11:11

gsamaras


C++17 introduced the maybe_unused attribute, which may help in your case. It can be applied to a variable to indicate that it may be unused:

[[maybe_unused]] const auto & something = Something<>{1};
like image 42
lisyarus Avatar answered Nov 10 '22 10:11

lisyarus