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);
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).
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.
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).
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 .
Use const T & arg
if sizeof(T)>sizeof(void*)
and use T arg
if sizeof(T) <= sizeof(void*)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With