Search code examples
c++c++11misra

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...


Solution

  • Try initialising the default parameter outside of the function declaration:

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