avva: (Default)
[personal profile] avva
C++ Rvalue References Explained

Отличная статья об одном из новшеств стандарта C++11 - так называемых "rvalue references". Оказывается, это совсем не страшная штука, и в этой статье всего из 11 страниц автор подробно объясняет, зачем они нужны, как их использовать, и почему, если вы собираетесь использовать rvalue references вместе с exceptions в одном и том же коде, лучше сразу застрелиться.

Процитирую прекрасную таблицу ссылок на ссылки:
  • A& & becomes A&
  • A& && becomes A&
  • A&& & becomes A&
  • A&& && becomes A&&

Date: 2012-11-04 05:13 pm (UTC)
From: [identity profile] helvegr.livejournal.com
Мне ещё вот это (http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Scott-Meyers-Universal-References-in-Cpp11) понравилось:

Given that rvalue references are declared using "&&", it seems reasonable to assume that the presence of "&&" in a type declaration indicates an rvalue reference. That is not the case:

Widget&& var1 = someWidget; // here, "&&" means rvalue reference
 
auto&& var2 = var1; // here, "&&" does not mean rvalue reference
 
template<typename T>
 
void f(std::vector&& param); // here, "&&" means rvalue reference
 
template<typename T>
 
void f(T&& param); // here, "&&" does not mean rvalue reference

In this article, I describe the two meanings of "&&" in type declarations, explain how to tell them apart, and introduce new terminology that makes it possible to unambiguously communicate which meaning of "&&" is intended. Distinguishing the different meanings is important, because if you think "rvalue reference" whenever you see "&&" in a type declaration, you'll misread a lot of C++11 code.
Edited Date: 2012-11-04 05:13 pm (UTC)

Date: 2012-11-04 05:15 pm (UTC)
From: [identity profile] avva.livejournal.com
Аааааа, это прекрасно, спасибо :)

Date: 2012-11-04 06:31 pm (UTC)
From: [identity profile] chainiksu.livejournal.com
О, а вот и расплата за выход С++ за пределы множества контекстно-свободных языков.

Date: 2012-11-04 07:11 pm (UTC)
From: [identity profile] amosk.livejournal.com
Какая еще расплата?
rvalue-ref были введены исключительно для оптимизации.
Если рассматривать в этом разрезе, то все вышеприведенные правила выведения типов очень логичны и интуитивно понятны.

Date: 2012-11-04 10:21 pm (UTC)
From: [identity profile] chainiksu.livejournal.com
Вот это:
template<typename T> void f(std::vector&& param); // here, "&&" means rvalue reference

template<typename T> void f(T&& param); // here, "&&" does not mean rvalue reference

- интуитивно понятно? Лолшто?
Edited Date: 2012-11-04 10:22 pm (UTC)

Date: 2012-11-04 08:00 pm (UTC)
From: [identity profile] huzhepidarasa.livejournal.com
Даже C никогда не был контекстно-свободным. Foo(bar); — это объявление переменной или вызов функции? A C++ и подавно (goog://most+vexed+parse) хотя бы.

Date: 2012-11-04 10:19 pm (UTC)
From: [identity profile] chainiksu.livejournal.com
Ну в Сях это как бы "цветочки". В реальных программах проблемы если и возникают, они хотя бы отлавливаются компиляторами (ambitious-ошибки).
В плюсах с их перегрузкой операторов уже начинались серьезные проблемы, когда один компилятор читал так, а другой иначе, и оба генерировали код, и оба формально были правы.
Но вот то, что сейчас, это уже за гранью борьбы бабла и зла.

ain't the first time

Date: 2012-11-05 04:12 am (UTC)
From: [identity profile] alexei lebedev (from livejournal.com)
violation of CSG:

a < b > c;

could be a declaration of variable c of type a< b > (instantiation of template a with argument b), or it could be 2 comparisons.


a b(c(d));

could be declaration of variable b of type a, initialized with value d which is cast to type c,
or it could be a declaration of function b which takes argument d of type c and returns a.

even in classic C,

(a) & (b);

could mean address of b being cast to type a, or bitwise and of values a and b; C resolves the ambiguity by checking whether a is a type. It gets worse in C++ because meaning of a can be different due to complicated lookup rules.

I could go on, but you get the point.
Edited Date: 2012-11-05 04:14 am (UTC)

December 2025

S M T W T F S
  123 4 56
78 9 10 11 1213
1415 1617181920
21 22 23 24 2526 27
28293031   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Dec. 28th, 2025 02:37 pm
Powered by Dreamwidth Studios