Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"const T &arg" vs. "T arg"

Tags:

Which of the following examples is the better way of declaring the following function and why?

void myFunction (const int &myArgument); 

or

void myFunction (int myArgument); 
like image 550
Etan Avatar asked Oct 14 '09 15:10

Etan


People also ask

What is const T & in C++?

const T* would only forbid you to modify anything the pointer points to, but it allows you (within the bounds of the language) to inspect the value at *(foo+1) and *(foo-1) . Use this form when you're passing pointers to immutable arrays (such as a C string you're only supposed to read).

What is a const function?

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.

When to use const C++?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).

How do you make a variable constant in C++?

To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .


2 Answers

Use const T & arg if sizeof(T)>sizeof(void*) and use T arg if sizeof(T) <= sizeof(void*)

like image 100
Alexey Malistov Avatar answered Oct 09 '22 01:10

Alexey Malistov


They do different things. const T& makes the function take a reference to the variable. On the other hand, T arg will call the copy constructor of the object and passes the copy. If the copy constructor is not accessible (e.g. it's private), T arg won't work:

class Demo {     public: Demo() {}      private: Demo(const Demo& t) { }  };  void foo(Demo t) { }  int main() {     Demo t;     foo(t); // error: cannot copy `t`.     return 0; } 

For small values like primitive types (where all matters is the contents of the object, not the actual referential identity; say, it's not a handle or something), T arg is generally preferred. For large objects and objects that you can't copy and/or preserving referential identity is important (regardless of the size), passing the reference is preferred.

Another advantage of T arg is that since it's a copy, the callee cannot maliciously alter the original value. It can freely mutate the variable like any local variables to do its work.

like image 38
mmx Avatar answered Oct 08 '22 23:10

mmx