Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "most important const" have to be const?

Tags:

c++

constants

In http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ it mentions "most important const" where by C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself. I was wondering why c++ only allows the lifetime of the object to be lengthened when the reference is const and not when it isn't? What is the rational behind the feature and why does it have to be const?

like image 291
dan Avatar asked Apr 14 '14 14:04

dan


People also ask

When should we use a const reference and why?

When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.

Should I always use const reference?

Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter. You can always add const, but not take it away (not without a const cast which is a really bad idea).


2 Answers

Here's an example:

void square(int &x) {   x = x * x; }  int main() {   float f = 3.0f;    square(f);    std::cout << f << '\n'; } 

If temporaries could bind to non-const lvalue references, the above would happily compile, but produce rather surprising results (an output of 3 instead of 9).

like image 59
Angew is no longer proud of SO Avatar answered Sep 27 '22 15:09

Angew is no longer proud of SO


Consider the following:

int& x = 5; x = 6; 

What should happen if this was allowed? By contrast, if you did

const int& x = 5; 

there would be no legal way to modify x.

like image 43
Luchian Grigore Avatar answered Sep 27 '22 17:09

Luchian Grigore