lundi 19 août 2019

Avoiding exceptions in default parameters

I have a function declaration like this:

void foo(std::string const &bar = std::string(""));

Now, we are using MISRA C++, and our code verifier gives an error on the default value's constructor:

RULE 15-5-3: The terminate() function shall not be called implicitly.

I understand that somewhere in the creation of the default parameter there may be a string construction (a sensible compiler would no doubt optimise it out, but MISRA C++'s rules cover stupid compilers too), that is, it is possible to translate:

foo();

To

std::string tmp(std::string("")); // May run out of memory, etc
foo(tmp);

However, is there some way round this, bar the obvious:

void foo(std::string const &bar);
void foo() { foo(std::string("")); }

This might get messy with multiple optional parameters, however...

Aucun commentaire:

Enregistrer un commentaire