Telegram Group & Telegram Channel
#advice

std::unreachable - безопасная стрельба в ногу 🔫

В C++23 стандартизировали метод std::unreachable, у которого лютое описание: invokes undefined behavior.

(До C++23 на linux можно использовать __builtin_unreachable)

Бывают случаи, когда совершенно точно известно, что значения аргумента в функции - ограниченное множество, но от нас все равно требуется что-то вернуть из функции при "недостижимых" значениях.

Пусть совершенно точно известно, что метод magic_func принимает только значения 1 или 3:
int magic_func(int value) {
switch (value) {
case 1:
return 100;
case 3:
return 500;
default:
/* ???????????? */
}
}
Нужно написать бесполезный код - что делать при значении не равном 1 или 3. Обычно делают два варианта:
    return 0; // возврат мусорного значения
throw std::exception(); // бросание мусорного исключения

Лишний код генерирует лишние инструкции - ссылка на godbolt.

Инструкция unreachable никакой семантики не имеет, и нужна чтобы показать компилятору, что данный участок кода "недостижим". Компилятор может как-то оптимизировать этот участок кода.
undefined behaviour значит, что в этом участке кода может происходить всё что захочет компилятор.

В нашем случае, если написать unreachable (ссылка на godbolt), компилятор выкинет лишнюю проверку и код станет таким:
int magic_func(int value) {
if (value == 1) {
return 100;
}
return 500;
}
Please open Telegram to view this post
VIEW IN TELEGRAM



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

#advice

std::unreachable - безопасная стрельба в ногу 🔫

В C++23 стандартизировали метод std::unreachable, у которого лютое описание: invokes undefined behavior.

(До C++23 на linux можно использовать __builtin_unreachable)

Бывают случаи, когда совершенно точно известно, что значения аргумента в функции - ограниченное множество, но от нас все равно требуется что-то вернуть из функции при "недостижимых" значениях.

Пусть совершенно точно известно, что метод magic_func принимает только значения 1 или 3:

int magic_func(int value) {
switch (value) {
case 1:
return 100;
case 3:
return 500;
default:
/* ???????????? */
}
}
Нужно написать бесполезный код - что делать при значении не равном 1 или 3. Обычно делают два варианта:
    return 0; // возврат мусорного значения
throw std::exception(); // бросание мусорного исключения

Лишний код генерирует лишние инструкции - ссылка на godbolt.

Инструкция unreachable никакой семантики не имеет, и нужна чтобы показать компилятору, что данный участок кода "недостижим". Компилятор может как-то оптимизировать этот участок кода.
undefined behaviour значит, что в этом участке кода может происходить всё что захочет компилятор.

В нашем случае, если написать unreachable (ссылка на godbolt), компилятор выкинет лишнюю проверку и код станет таким:
int magic_func(int value) {
if (value == 1) {
return 100;
}
return 500;
}

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/58

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

Channels are not fully encrypted, end-to-end. All communications on a Telegram channel can be seen by anyone on the channel and are also visible to Telegram. Telegram may be asked by a government to hand over the communications from a channel. Telegram has a history of standing up to Russian government requests for data, but how comfortable you are relying on that history to predict future behavior is up to you. Because Telegram has this data, it may also be stolen by hackers or leaked by an internal employee. Since its launch in 2013, Telegram has grown from a simple messaging app to a broadcast network. Its user base isn’t as vast as WhatsApp’s, and its broadcast platform is a fraction the size of Twitter, but it’s nonetheless showing its use. While Telegram has been embroiled in controversy for much of its life, it has become a vital source of communication during the invasion of Ukraine. But, if all of this is new to you, let us explain, dear friends, what on Earth a Telegram is meant to be, and why you should, or should not, need to care. The channel appears to be part of the broader information war that has developed following Russia's invasion of Ukraine. The Kremlin has paid Russian TikTok influencers to push propaganda, according to a Vice News investigation, while ProPublica found that fake Russian fact check videos had been viewed over a million times on Telegram. Telegram was co-founded by Pavel and Nikolai Durov, the brothers who had previously created VKontakte. VK is Russia’s equivalent of Facebook, a social network used for public and private messaging, audio and video sharing as well as online gaming. In January, SimpleWeb reported that VK was Russia’s fourth most-visited website, after Yandex, YouTube and Google’s Russian-language homepage. In 2016, Forbes’ Michael Solomon described Pavel Durov (pictured, below) as the “Mark Zuckerberg of Russia.” On December 23rd, 2020, Pavel Durov posted to his channel that the company would need to start generating revenue. In early 2021, he added that any advertising on the platform would not use user data for targeting, and that it would be focused on “large one-to-many channels.” He pledged that ads would be “non-intrusive” and that most users would simply not notice any change.
from us


Telegram C++95
FROM American