g++ warn_unused_result

介绍

在编程过程中,有的函数我们需要确保函数的返回值必须被使用。但是如果函数使用者直接调用函数且不使用函数的返回值的话,g++ 不会给出warning。这样可能会导致很难寻觅的bug。如调用realloc函数,函数调用者必须使用函数的返回值获得重新分配内存的指针。
利用g++ common function attributes 中提供的warn_unused_result 可以保证函数的返回值在没有被使用的时候提示warning,如果在编译选项添加-Werror, 则在编译时就会提示编译错误。关于更多 g++ common function attributes 参见https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html

示例

测试代码如下

/*************************************************************************
    > File Name: warn_unused_result.cpp
    > Author: ce39906
    > Mail: [email protected]
    > Created Time: 2018-08-24 14:04:00
 ************************************************************************/

__attribute__ ((warn_unused_result))
int f(int x)
{
    return x / 2;
}

__attribute__ ((warn_unused_result))
double f1()
{
    return 0.;
}

class EmptyClass
{
};

__attribute__ ((warn_unused_result))
EmptyClass f2()
{
    return EmptyClass();
}

class NotEmptyClass
{
    int a;
};

__attribute__ ((warn_unused_result))
NotEmptyClass f3()
{
    return NotEmptyClass();
}

int main()
{
    // cause unused_result warning
    f(3);
    // no unused_result warning
    int x = f(3);
    (void) x;
    // cause unused_result warning
    f1();
    // cause unused_result warning
    f2();
    // no unused_result warning. WHY??
    f3();

    return 0;
}

编译

g++ -Wall -Wextra warn_unused_result.cpp -o warn_unused_result

编译输出如下
res
其中比较奇怪的现象是当函数返回一个非空的对象时,不会产生warning,比较诡异,至今没找到合理解释。

猜你喜欢

转载自blog.csdn.net/carbon06/article/details/82017545
g++