Is it bad to make a reference parameter optional by giving it a default value? Like here:

int Parse(std::string filename, std::string& error = (std::string)"");

Here, the caller of the function may pass an optional std::string that will be filled with an error message if there is one. Is this considered "ok", both as far as being safe, good code and having good style?

9 Years
Discussion Span
Last Post by Duoas

It's legal construct (better use more accurate std::string(""), avoid old C style casts).

I don't like this style (tastes differ). It's an ineffective code (string constructor works on every call for default argument). It's some confusing code (pass by reference means inout parameter as ususlly).

In that case I prefer const char* msg = 0 - programmer's intentions are more evident...


There is nothing wrong with it. You'll just get a reference to a temporary default.

The best advice is to write const std::string& error = std::string() as your argument. This will take strings and char*s equally.

Hope this helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.