Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const T& vs. T&&

I have the following function:

T foo();

And, in another function, I'm playing with the returned T value, like:

const T& t = foo();

or

T&& t = foo();

I want to ask:

  1. Are both equivalent?

  2. Memory-wise, what are the difference between these two approaches?

  3. I know that on the first approach the temporary value lifetime matches the reference lifetime. The same occurs when using the rvalue reference?

  4. Should I even consider using a const rvalue reference (const T&&)?

I'm using the first approach, that is what I'm used to and attends me fine. I'm still wrapping my head around rvalue references and C++11 goods.

like image 863
talles Avatar asked Feb 10 '13 01:02

talles


People also ask

What is 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.

What is the const in c++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

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).

Why use const in c++ function?

A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended practice to make as many functions const as possible so that accidental changes to objects are avoided.


1 Answers

  1. No, they have different types.

  2. Implementation-defined, but there's unlikely to be any difference.

  3. Lifetime extension works the same for rvalue and lvalue references. But the rule is more complicated than "the temporary value lifetime matches the reference lifetime".

  4. Probably not. I certainly wouldn't go looking for places to use it. If you have a use for it, it had better be such an significant improvement to justify the use of such an unusual combination and the confusion that will ensue when people read it in the future.

like image 110
Ben Voigt Avatar answered Sep 17 '22 15:09

Ben Voigt