When should I use [[maybe_unused]]?

喜欢而已 提交于 2019-11-29 10:48:35

问题


What is good about using [[maybe_unused]]? Consider

int winmain(int instance, int /*prevInstance*/, const char */*cmdline*/, int show);

int winmain(int instance, [[maybe_unused]] int prevInstance, [[maybe_unused]] const char *cmdline, int show);

Some might insist that using comments is ugly, because this keyword was made and intended to be used under these circumstances, and I totally agree with it, but the maybe_unused keywords seems a bit too long to me, making the code slightly harder to read.

I would like to follow the standard as "strictly" as I can, but is it worth using?


回答1:


If the parameter is definitely unused, [[maybe_unused]] is not particularly useful, unnamed parameters and comments work just fine for that.

[[maybe_unused]] is mostly useful for things that are potentially unused, like in

void fun(int i, int j) {
    assert(i < j);
    // j not used here anymore
}

This can't be handled with unnamed parameters, but if NDEBUG is defined, will produce a warning because j is unused.

Similar situations can occur when a parameter is only used for (potentially disabled) logging.




回答2:


Baum mit Augen's answer is the definitive and undisputed explanation. I just want to present another example, which doesn't require macros. Specifically, C++17 introduced the constexpr if construct. So you may see template code like this (bar the stupid functionality):

#include <type_traits>

template<typename T>
auto add_or_double(T t1, T t2) noexcept {
    if constexpr (std::is_same_v<T, int>)
        return t1 + t2;
    else
        return t1 * 2.0;
}

int main(){
    add_or_double(1, 2);
    add_or_double(1.0, 2.0);
}

As of writing this, GCC 8.0.1 warns me about t2 being unused when the else branch is the instantiated one. The attribute is indispensable in a case like this too.



来源:https://stackoverflow.com/questions/49320810/when-should-i-use-maybe-unused

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!