简体   繁体   中英

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.

  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.

  1. They are basically the same (lifetime extension of temporaries applies) but one is const and one is not.
  2. There probably isn't any difference "memory-wise" but that's implementation-dependent.
  3. Yes.
  4. I can't imagine a case where you'd want that.

However, move-semantics really make the technique you're using antiquated. It was originally intended to let people avoid making unnecessary copies, but now with move semantics, what would be expensive before is now practically free and much more readable.

If you ever wondered when and if to use &&, I strongly recommend watching

http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Scott-Meyers-Universal-References-in-Cpp11

Imho, it's definitly worth investing the time.

To my understanding:

1+2) Depends on the type of T

3) No impact on lifetime off the referenced value. Side note : whatever T&& ends up to be type wise, it's got a name now: t , and therefore is an l value.

4) Kind of directed towards myself: How do you move from something that's const?

Best Jochen

edit: added blank lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM