Keyword const

My code does not compile.

int foobar() { // code return 5; } int main() { int &p = foobar(); // error // code const int& x = foobar(); //compiles } 

Why does adding the const keyword make code compilation?

+4
source share
3 answers

In C ++, temporary entries cannot be bound to mutable references.

IN

  int &p = foobar(); 

the rvalue foobar() expression creates a temporary one that cannot be bound to p , because it is a non-constant reference.

  const int &x = foobar(); 

Attaching a temporary to x , which is a reference to const, extends its lifespan. This is completely legal.

+9
source

Because foobar() returns by value; this result is temporary. You cannot have a temporary permalink.

If not, what would this code do?

 int &x = foobar(); x = 1; // Where are we writing to? 
+4
source

As others have said, you can take a constant, but not a non-constant reference to a temporary one.

In practice, there may be dangers in providing non-constant references to temporary:

 #include <iostream> void foo(int &i) { i = 5; } int main() { long l = 4; foo(l); std::cout << l << "\n"; } 

Now l can be implicitly converted to int , therefore, if a reference was not allowed to a constant, then presumably foo will be passed a reference to the result of this conversion, the same as in fact, if foo accepts const int & . The assignment will be performed in the temporary, and then discarded when the temporary is destroyed. This is much more likely to be a confusing mistake than this should be the intended result.

I don’t know if there is a clear set of rules allowing to refer to non-constant links to temporary situations in some situations, but not dangerous / annoying, but even if the C ++ standard did not include them. Note that C ++ 0x has rvalue links that allow you to perform some additional actions with temporary parameters that cannot be performed in C ++ 03.

+2
source

All Articles