Telegram Group & Telegram Channel
#compiler

Как в компиляторе реализуют NRVO?
(и почему он не всегда работает)

Для подробной информации о явлении можно прочитать на cppreference.

NRVO (Named Return Value Optimization) - это оптимизация из класса copy elision. Copy elision это отсутствие вызова конструкторов копирования/мува за счёт того, что объект изначально создается в целевом месте.

Оптимизация RVO (Return Value Optimization) выглядит чуть проще:
std::string foo1() {
return std::string("bar");
}
std::string f = foo1();
Компилятор может понять, что никакой нужды в вызове copy/move нет - надо заранее выделить место на стеке под std::string f и создать строку туда.

Даже если copy/move ctors имеют побочные эффекты, их все равно не вызовут. Эти конструкторы можно объявить = delete, или объявить без определения, или сделать private - это ни на что не повлияет.

Эта оптимизация старая, все компиляторы ее делают, а с C++17 она стала обязательной при определенных условиях.

Оптимизация NRVO сложнее, но она не обязательная (в отличие от RVO) - компилятор может сгенерировать суб-оптимальный код.
Условие здесь похожее - если у нас все return xxx; внутри метода возвращают один и тот же xxx;, то в таком случае тоже не происходит copy/move:
std::string foo2() {
std::string y = "I'm a redundant string";
std::string x = "sample text";
if (x.size() % 2 == 0) {
return x;
}
x += "xxx";
return x;
}
std::string f = foo2(); // без копирования

Как мы видим, все return возвращают одно и то же, поэтому NRVO сработает. Если бы у нас где-нибудь был return y; или return std::move(x);, то NRVO бы не сработал.

Как вычисление NRVO происходит в компиляторе Clang?

Во время парсинга файла Clang держит стек scope (думаю +- понятно для чего нужны скоупы). Одни scope вложены в другие scope, и образуют дерево из scope.
Свой scope создается для каждого метода, каждого класса, каждого if-выражения, каждого for-loop, и так далее. Самый "высокоуровневый" scope это scope Translation Unit-а.



group-telegram.com/cxx95/11
Create:
Last Update:

#compiler

Как в компиляторе реализуют NRVO?
(и почему он не всегда работает)

Для подробной информации о явлении можно прочитать на cppreference.

NRVO (Named Return Value Optimization) - это оптимизация из класса copy elision. Copy elision это отсутствие вызова конструкторов копирования/мува за счёт того, что объект изначально создается в целевом месте.

Оптимизация RVO (Return Value Optimization) выглядит чуть проще:

std::string foo1() {
return std::string("bar");
}
std::string f = foo1();
Компилятор может понять, что никакой нужды в вызове copy/move нет - надо заранее выделить место на стеке под std::string f и создать строку туда.

Даже если copy/move ctors имеют побочные эффекты, их все равно не вызовут. Эти конструкторы можно объявить = delete, или объявить без определения, или сделать private - это ни на что не повлияет.

Эта оптимизация старая, все компиляторы ее делают, а с C++17 она стала обязательной при определенных условиях.

Оптимизация NRVO сложнее, но она не обязательная (в отличие от RVO) - компилятор может сгенерировать суб-оптимальный код.
Условие здесь похожее - если у нас все return xxx; внутри метода возвращают один и тот же xxx;, то в таком случае тоже не происходит copy/move:
std::string foo2() {
std::string y = "I'm a redundant string";
std::string x = "sample text";
if (x.size() % 2 == 0) {
return x;
}
x += "xxx";
return x;
}
std::string f = foo2(); // без копирования

Как мы видим, все return возвращают одно и то же, поэтому NRVO сработает. Если бы у нас где-нибудь был return y; или return std::move(x);, то NRVO бы не сработал.

Как вычисление NRVO происходит в компиляторе Clang?

Во время парсинга файла Clang держит стек scope (думаю +- понятно для чего нужны скоупы). Одни scope вложены в другие scope, и образуют дерево из scope.
Свой scope создается для каждого метода, каждого класса, каждого if-выражения, каждого for-loop, и так далее. Самый "высокоуровневый" scope это scope Translation Unit-а.

BY C++95


Warning: Undefined variable $i in /var/www/group-telegram/post.php on line 260

Share with your friend now:
group-telegram.com/cxx95/11

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

At the start of 2018, the company attempted to launch an Initial Coin Offering (ICO) which would enable it to enable payments (and earn the cash that comes from doing so). The initial signals were promising, especially given Telegram’s user base is already fairly crypto-savvy. It raised an initial tranche of cash – worth more than a billion dollars – to help develop the coin before opening sales to the public. Unfortunately, third-party sales of coins bought in those initial fundraising rounds raised the ire of the SEC, which brought the hammer down on the whole operation. In 2020, officials ordered Telegram to pay a fine of $18.5 million and hand back much of the cash that it had raised. In 2018, Russia banned Telegram although it reversed the prohibition two years later. On February 27th, Durov posted that Channels were becoming a source of unverified information and that the company lacks the ability to check on their veracity. He urged users to be mistrustful of the things shared on Channels, and initially threatened to block the feature in the countries involved for the length of the war, saying that he didn’t want Telegram to be used to aggravate conflict or incite ethnic hatred. He did, however, walk back this plan when it became clear that they had also become a vital communications tool for Ukrainian officials and citizens to help coordinate their resistance and evacuations. "The inflation fire was already hot and now with war-driven inflation added to the mix, it will grow even hotter, setting off a scramble by the world’s central banks to pull back their stimulus earlier than expected," Chris Rupkey, chief economist at FWDBONDS, wrote in an email. "A spike in inflation rates has preceded economic recessions historically and this time prices have soared to levels that once again pose a threat to growth." And while money initially moved into stocks in the morning, capital moved out of safe-haven assets. The price of the 10-year Treasury note fell Friday, sending its yield up to 2% from a March closing low of 1.73%.
from us


Telegram C++95
FROM American