Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of Default parameters in C++

I stumbled through an example from "Effective C++ in an Embedded Environment" by Scott Meyers where two ways of using default parameters were described: one which was described as costly and the other as a better option.

I am missing the explanation of why the first option might be more costly compared to the other one.

void doThat(const std::string& name = "Unnamed"); // Bad  const std::string defaultName = "Unnamed"; void doThat(const std::string& name = defaultName); // Better 
like image 333
bentz123 Avatar asked Feb 20 '18 08:02

bentz123


People also ask

What is default parameter in C?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument.

Can you have default parameters in C?

There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.

What is the default value of parameter?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

What are the parameters that are default?

Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.


1 Answers

In the first one, a temporary std::string is initialised from the literal "Unnamed" each time the function is called without an argument.

In the second case, the object defaultName is initialised once (per source file), and simply used on each call.

like image 176
Angew is no longer proud of SO Avatar answered Nov 03 '22 06:11

Angew is no longer proud of SO