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&&
Page 1 of 3 << [1] [2] [3] >>

Date: 2012-11-04 01:56 pm (UTC)
From: [identity profile] ak-47.livejournal.com
Таблица напомнила мне русскую пословицу: один сын - не сын, два сына - полсына, три сына - сын.

А вообще, из всех новшеств Ц++11, эти новые ссылки самые неинтуитивные. Хотя, может это старость наступает...

Date: 2012-11-04 02:20 pm (UTC)
From: [identity profile] blacklion.livejournal.com
Где-то мне мерещится тег <irony> :)

Date: 2012-11-04 02:34 pm (UTC)
From: [identity profile] trurle.livejournal.com
Описание языка PL-I занимало целую полку, не думаю что существовал человек, овладевший навыками программирования на PL-I в полном объеме.

Похоже что C++ стремительно деградирует к этому состоянию. Вообще, все стремительно портится, последние времена наступают.

Date: 2012-11-04 02:50 pm (UTC)
From: [identity profile] bealex.livejournal.com
После пятого амперсанда затерялся.

Date: 2012-11-04 03:01 pm (UTC)
From: [identity profile] winpooh.livejournal.com
Мне кажется, основная премудрость там состоит в двух строчках на стр.3:
Rvalue references allow a function to branch at compile time (via overload resolution)
on the condition "Am I being called on an lvalue or an rvalue?".

"Остальное - комментарий".

Date: 2012-11-04 03:19 pm (UTC)
From: [identity profile] igorlord.livejournal.com
The first page left me totally confused about what definition of l-value he will use for the remainder of the article.

Consider:
const int r = 37;

Is r an l-value or r-value? By the first definition, it is an r-value, since it cannot be on the left side of assignment. But by the second definition, it is an l-value, since it refers to a memory location, and its address can be taken.

Date: 2012-11-04 03:25 pm (UTC)
From: [identity profile] spamsink.livejournal.com
Да. Как только я это в свое время понял сам при чтении разнообразных operator+ для std::string, наступило просветление.

Date: 2012-11-04 03:35 pm (UTC)
From: [identity profile] dimrub.livejournal.com
Первое определение - из С, второе - из С++. Там даже вот такая фраза есть:

In C++, this is still useful as a first, intuitive approach to lvalues and rvalues. However, C++ with its user-defined types has introduced some subtleties regarding modifiability and assignability that cause this definition to be incorrect.

Date: 2012-11-04 03:40 pm (UTC)
From: [identity profile] igorlord.livejournal.com
My example is pure C with no semantic differences introduced by C++. That is exactly why his statement is confusing, since it implies that the second definition should just extend to first definition to cover additional semantics introduced by C++.

Still, it is now clear that he means to use the second definition in my case.

Date: 2012-11-04 03:44 pm (UTC)
From: [identity profile] huzhepidarasa.livejournal.com
И эти люди запрещают мне ковыряться в монадах.

Date: 2012-11-04 03:52 pm (UTC)
From: [identity profile] dimrub.livejournal.com
Программист на С++ имеет все шансы состариться и уйти на пенсию, всю жизнь пользуясь rvalue references, и не зная этого (грубо говоря, если я не пишу performance intensive libraries, то они мне не нужны). У программиста на Хаскелле возможности не знать, что такое монады, нет.

Date: 2012-11-04 03:58 pm (UTC)
From: [identity profile] cmm.livejournal.com
грубо говоря, если я не пишу performance intensive libraries, то они мне не нужны

зачем же тогда мучить себя крестами?
(это риторический вопрос).

Date: 2012-11-04 04:09 pm (UTC)
From: [identity profile] huzhepidarasa.livejournal.com
Wishful thinking. У программиста на Хаскеле есть все возможности умереть, не узнав, что такое монада. Он просто будет думать, что знает.

Date: 2012-11-04 04:10 pm (UTC)
From: [identity profile] cmm.livejournal.com
"most, in fact, do".

Date: 2012-11-04 04:16 pm (UTC)
From: [identity profile] huzhepidarasa.livejournal.com
Хочется верить, что большинство программистов на Хаскеле пока еще все же живо. Так что не все потеряно, по крайней мере теоретически.

Date: 2012-11-04 04:24 pm (UTC)
From: [identity profile] asox.livejournal.com
Is r an l-value or r-value?

r-value

Иначе код

const int r = 37;
char s[r];

был бы валиден (периодически встречаю утверждение, что так оно и есть, но, почему-то, компиляторы обычно ругаются).

Date: 2012-11-04 04:25 pm (UTC)
From: [identity profile] huzhepidarasa.livejournal.com
И еще. Само наличие в языке темных углов вредно и опасно, даже если считать, что большинству программистов заходить туда не нужно. Как сказал поэт, Совершите вы массу открытий//Иногда не желая того O:-)

Date: 2012-11-04 04:26 pm (UTC)
From: [identity profile] asox.livejournal.com
Вот именно.

Date: 2012-11-04 04:34 pm (UTC)
From: [identity profile] pilpilon.livejournal.com
не связанные вещи.

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 05:27 pm (UTC)
From: [identity profile] senecarus.livejournal.com
Как хорошо, что я с этим завязал.

Date: 2012-11-04 05:51 pm (UTC)
From: [identity profile] smilga.livejournal.com
Можно подумать, есть зачем мучить себя крестами даже и человеку, пишущему performance intensive libraries.

Date: 2012-11-04 05:53 pm (UTC)
From: [identity profile] cmm.livejournal.com
"это другой вопрос".

Date: 2012-11-04 06:27 pm (UTC)
From: [identity profile] chainiksu.livejournal.com
Ну, у человека, пишущего performance intensive libraries, всего две альтернативы - с крестами и без.
Page 1 of 3 << [1] [2] [3] >>

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 12:16 pm
Powered by Dreamwidth Studios