Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ const lvalue references

Assuming I have:

  • class A which is non-copyable
  • class B which has as a member, const A& a (and takes an A in its constructer and sets it in its initialization list)
  • a function A GenerateA();

Does this mean that it should be valid to do: B(GenerateA()) ?

i.e, does the const ref mean that no copy of the A that generateA() returns is done? And does that mean that the scope of the returned temporary is extended for as long as B exists?

EDIT: Addon question from the comments: Is it acceptable to return a A& from GenerateA() to a local A, if the lvalue is a const A&?

Thanks!

like image 306
please delete me Avatar asked Nov 10 '10 04:11

please delete me


People also ask

Is const reference an lvalue?

Such a reference is called an lvalue reference to a const value (sometimes called a reference to const or a const reference). In the above program, we bind const reference ref to modifiable lvalue x . We can then use ref to access x , but because ref is const, we can not modify the value of x through ref .

Can references be const?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

What is an lvalue reference?

“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&' before the name of the variable.

What is a const rvalue reference?

You probably haven't seen any practical code that uses const rvalue references ( const T&& ). And that's not really surprising. The main purpose of rvalue references is to allow us to move objects instead of copying them. And moving the state of an object implies modification.


1 Answers

If A is non-copyable, then the function A GenerateA() is invalid since returning by value requires creating a copy.

If the function returns a reference instead (i.e. A &GenerateA()) and the reference is to a locally created A object, it becomes invalid as soon as the function exits. C++ doesn't have any form of garbage collection, so there is no way to "extend" the lifetime of an object as long as it is in use.

like image 172
casablanca Avatar answered Sep 29 '22 01:09

casablanca