主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C++:2023 Rule 0.1.2

The value returned by a function shall be used

自 R2024b 起

描述

规则定义

The value returned by a function shall be used 1 .

理由

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

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

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

Polyspace 实现

如果出现以下情况,检查项将报告违规:

  • 返回类型为非 void 的函数返回的值不会被使用,也不会显式转换为 void 类型。

  • 使用函数调用语法调用 lambda、std::function 对象或用户定义的 operator(),其返回值不会被使用。

检查项不会报告函数 memcpymemsetmemmovestrcpystrncpystrcatstrncat 的违规情况,因为这些函数只是返回其第一个参量的指针。

故障排除

如果您预期会出现违规,而 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
}

在此示例中,Polyspace 报告对 assignMemory() 函数和 std::vector::erase() 方法的调用违反了规则,因为它们的返回值未被使用或未转换为 void

检查信息

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

版本历史记录

在 R2024b 中推出


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++:2008

  • MISRA C++:2023

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