Telegram Group & Telegram Channel
std::move ничего не двигает 🤯

Вот типичная ошибка, которая встречается даже у опытных:


std::string foo() {
std::string s = "hello";
return std::move(s); //
}


Кажется, что std::move здесь «ускоряет» возврат. Но это зло. На самом деле, компилятор и без std::move применяет Return Value Optimization (RVO) и возвращает s без копирования. А вот std::move ломает RVO — теперь вызывается перемещающий конструктор, и компилятор не может это оптимизировать.

Результат:

* return s; — возможно, вообще без затрат (RVO).
* return std::move(s);гарантированно перемещение (дороже, чем RVO).

🔑 Правило: никогда не пиши std::move при возврате локальной переменной по значению. Доверься компилятору.

Когда std::move действительно нужен? Например:


void bar(std::string&& s) {
auto local = std::move(s); // перемещаем из rvalue-ссылки
}


Здесь всё логично: мы явно говорим, что хотим «украсть» содержимое.

Вывод: std::move — это не перемещение, а обещание, что объект можно обобрать. А перемещать будет уже компилятор.

➡️ @cpp_geek



tg-me.com/cpp_geek/317
Create:
Last Update:

std::move ничего не двигает 🤯

Вот типичная ошибка, которая встречается даже у опытных:


std::string foo() {
std::string s = "hello";
return std::move(s); //
}


Кажется, что std::move здесь «ускоряет» возврат. Но это зло. На самом деле, компилятор и без std::move применяет Return Value Optimization (RVO) и возвращает s без копирования. А вот std::move ломает RVO — теперь вызывается перемещающий конструктор, и компилятор не может это оптимизировать.

Результат:

* return s; — возможно, вообще без затрат (RVO).
* return std::move(s);гарантированно перемещение (дороже, чем RVO).

🔑 Правило: никогда не пиши std::move при возврате локальной переменной по значению. Доверься компилятору.

Когда std::move действительно нужен? Например:


void bar(std::string&& s) {
auto local = std::move(s); // перемещаем из rvalue-ссылки
}


Здесь всё логично: мы явно говорим, что хотим «украсть» содержимое.

Вывод: std::move — это не перемещение, а обещание, что объект можно обобрать. А перемещать будет уже компилятор.

➡️ @cpp_geek

BY C++ geek




Share with your friend now:
tg-me.com/cpp_geek/317

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

How Does Telegram Make Money?

Telegram is a free app and runs on donations. According to a blog on the telegram: We believe in fast and secure messaging that is also 100% free. Pavel Durov, who shares our vision, supplied Telegram with a generous donation, so we have quite enough money for the time being. If Telegram runs out, we will introduce non-essential paid options to support the infrastructure and finance developer salaries. But making profits will never be an end-goal for Telegram.

How Does Bitcoin Work?

Bitcoin is built on a distributed digital record called a blockchain. As the name implies, blockchain is a linked body of data, made up of units called blocks that contain information about each and every transaction, including date and time, total value, buyer and seller, and a unique identifying code for each exchange. Entries are strung together in chronological order, creating a digital chain of blocks. “Once a block is added to the blockchain, it becomes accessible to anyone who wishes to view it, acting as a public ledger of cryptocurrency transactions,” says Stacey Harris, consultant for Pelicoin, a network of cryptocurrency ATMs. Blockchain is decentralized, which means it’s not controlled by any one organization. “It’s like a Google Doc that anyone can work on,” says Buchi Okoro, CEO and co-founder of African cryptocurrency exchange Quidax. “Nobody owns it, but anyone who has a link can contribute to it. And as different people update it, your copy also gets updated.”

C geek from us


Telegram C++ geek
FROM USA