CPP_GEEK Telegram 347
std::exchange — простой способ менять значения и возвращать старые

Вместо того чтобы писать руками:


auto old = value;
value = new_value;
return old;


В modern C++ есть готовый инструмент - std::exchange (C++14+).


#include <utility>
#include <string>
#include <iostream>

int main() {
std::string s = "Hello";
auto old = std::exchange(s, "World");

std::cout << "old = " << old << ", s = " << s << '\n';
}


Вывод:


old = Hello, s = World


Когда полезно:

- Реализация move-конструкторов/операторов:


MyType(MyType&& other)
: data_(std::exchange(other.data_, nullptr)) {}

- Сброс состояния объектов и возвращение старого значения.
- Реализация одноразовых флагов (`once_flag` паттерн).

Плюсы:

- Одна строка вместо трёх.
- Читаемость выше — сразу видно, что мы заменяем значение и берём старое.

Помни: по умолчанию второе значение копируется/перемещается, так что это не нулевой по стоимости вызов.

➡️ @cpp_geek
4👍4👾1



tgoop.com/cpp_geek/347
Create:
Last Update:

std::exchange — простой способ менять значения и возвращать старые

Вместо того чтобы писать руками:


auto old = value;
value = new_value;
return old;


В modern C++ есть готовый инструмент - std::exchange (C++14+).


#include <utility>
#include <string>
#include <iostream>

int main() {
std::string s = "Hello";
auto old = std::exchange(s, "World");

std::cout << "old = " << old << ", s = " << s << '\n';
}


Вывод:


old = Hello, s = World


Когда полезно:

- Реализация move-конструкторов/операторов:


MyType(MyType&& other)
: data_(std::exchange(other.data_, nullptr)) {}

- Сброс состояния объектов и возвращение старого значения.
- Реализация одноразовых флагов (`once_flag` паттерн).

Плюсы:

- Одна строка вместо трёх.
- Читаемость выше — сразу видно, что мы заменяем значение и берём старое.

Помни: по умолчанию второе значение копируется/перемещается, так что это не нулевой по стоимости вызов.

➡️ @cpp_geek

BY C++ geek


Share with your friend now:
tgoop.com/cpp_geek/347

View MORE
Open in Telegram


Telegram News

Date: |

Channel login must contain 5-32 characters Just as the Bitcoin turmoil continues, crypto traders have taken to Telegram to voice their feelings. Crypto investors can reduce their anxiety about losses by joining the “Bear Market Screaming Therapy Group” on Telegram. How to create a business channel on Telegram? (Tutorial) Add up to 50 administrators The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers.
from us


Telegram C++ geek
FROM American