主要内容

MISRA C++:2008 Rule 0-1-7

R2026b

The value returned by a function having a non- void return type that is not an overloaded operator shall always be used

描述

The value returned by a function having a non- void return type that is not an overloaded operator shall always be used. 1

理由

未使用的返回值可能表明存在编码错误或疏忽。

重载运算符不在此规则范围内,因为它们的用法必须模拟内置运算符,而内置运算符可能不会使用其返回值。

如果要故意忽略函数的返回值,请将返回值强制转换为 void。

Polyspace 实现

如果未使用返回值或未将其显式强制转换为 void 类型,检查项会标记具有非 void 返回值的函数。

检查项不会标记 memcpy、memset、memmove、strcpy、strncpy、strcat、strncat 函数,因为这些函数只是返回指向其第一个参量的指针。

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示。

示例

全部展开

#include <iostream>
#include <new>
#include <algorithm>
#include <cstdint>
#include <vector>

int assignMemory(int * ptr)
{
    int res = 1;
    ptr = new (std::nothrow) int;
    if(ptr==NULL)
        {
            res = 0;
        }
    return res;
}

void main()
{
    int val;
    int status;
    std::vector<std::int8_t> numVec{10,10,20,20,30,40,50,50,60};

    assignMemory(&val);   //Noncompliant
    status = assignMemory(&val); //Compliant
    (void)assignMemory(&val); //Compliant

    numVec.erase(std::unique(numVec.begin(), numVec.end()), numVec.end());// Noncompliant
}

在此示例中,当 assignMemory() 函数和 std::vector::erase() 方法的返回值未被使用且未强制转换为 void 时,Polyspace 会针对调用该函数和方法报告违规。

检查信息

组:与语言无关的问题
类别:必需

版本历史记录

在 R2013b 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C:2025

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.