How to resolve this warning MISRA: C ++

Here is the code as below:

  std::stringstream os;

  os << std::hex; // MISRA warning on this line
  os << std::setw(2);
  os << std::setfill('0');

Warning: "Mandatory rule 8-4-4, function identifier used without" & "; or a partisan parameter list"

I can’t solve it, suggest a solution.

+4
source share
7 answers

Do what the warning says: take the function address:

os << &std::hex;
+5
source

How easy to use &as suggested?

#include <iomanip>
#include <iostream>
#include <sstream>

int main() {
    std::stringstream os;

    os << &std::hex; // Works with &
    os << std::setw(2);
    os << std::setfill('0');
    os << 13;

    std::cout << os.str() << "\n";
    return 0;
}

Yes, it works too .


What is the difference?

  • std::hex is a function reference
  • &std::hex is a function pointer

, ostream, , . -, MISRA , , , , .

+4

std::hex(std::cout);

std::cout << std::hex;

.

std::cout << &std::hex;

, .

, MISRA "" //. std::hex , - .

+2

os << std::hex;

basic_ostream<charT,traits>& basic_ostream::operator<<(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))

operator<<(), basic_ostream<>. std::hex.

operator<<() . , , :

os << &std::hex;    // makes the function pointer explicit using the & operator

std::hex(os);       // call the `std::hex` function using a normal function call syntax

// or directly call the function that `std::hex(os)` is specified to do:
os.setf(std::ios_base::hex, std::ios_base::basefield);

, MISRA .

+1

, , std:: stringstream . . , "error", std:: bas_alloc, .

http://www.cplusplus.com/reference/ios/ios/exceptions/

+1

, .

:

  • std::hex MISRA-.

    a) std::hex.

    b) std::hex. std::hex .

  • , std:: hex, , .

    a) .

    b) .

0

:

  • std::hex
  • do cout<<&std::hex
  • MISRA

, - icky.

, MISRA , - MISRA C ( , )

, .

, , , , , , - , , . , .

0

Source: https://habr.com/ru/post/1524441/


All Articles