Telegram Group & Telegram Channel
🧠 Задача с подвохом для продвинутых C++ разработчиков

🔹 Уровень: Advanced
🔹 Темы: std::vector, управление памятью, конструкторы/деструкторы, reserve() vs resize()

📌 Условие

Рассмотрим следующий код:


#include <iostream>
#include <vector>

struct Foo {
Foo() { std::cout << "Ctor\n"; }
~Foo() { std::cout << "Dtor\n"; }
Foo(const Foo&) { std::cout << "Copy\n"; }
Foo(Foo&&) noexcept { std::cout << "Move\n"; }
};

int main() {
std::vector<Foo> v;
v.reserve(3); // Резервируем место под 3 элемента

std::cout << "--- Pushing ---\n";
for (int i = 0; i < 3; ++i) {
v.push_back(Foo());
}

std::cout << "--- Done ---\n";
}


Вопросы

1. Что будет выведено на экран?
2. Почему reserve() не предотвращает конструкторы копирования/перемещения?
3. Что изменится, если заменить reserve(3) на resize(3)?

🔍 Разбор

Ожидаемый вывод:

--- Pushing ---
Ctor
Move
Dtor
Ctor
Move
Dtor
Ctor
Move
Dtor
--- Done ---
Dtor
Dtor
Dtor


🔧 Почему так происходит

- Foo() создаёт временный объект.
- push_back() вызывает перемещающий конструктор Move.
- Временный объект уничтожается (вызывается `Dtor`).
- reserve(3) выделяет память, но не создаёт объектов.

🔄 Если заменить `reserve(3)` на `resize(3)`

- resize(3) создаст 3 объекта Foo через конструктор по умолчанию.
- push_back(Foo()) добавит четвёртый, возможно вызовет realocation.
- Это может привести к копированию или перемещению уже созданных элементов.

⚠️ Подвох

Многие ошибочно считают, что reserve(n) создаёт n объектов. Но это не такreserve() только выделяет память, не вызывая конструкторы. Именно поэтому внутри push_back всё равно происходит перемещение или копирование.

🧠 Вывод

- reserve() — экономия на реаллокациях, без создания объектов.
- resize() — создаёт n объектов, вызывает конструкторы.
- Не путай эти методы — от этого зависит и производительность, и семантика.


// Резервирует память, не создаёт объекты
v.reserve(10);

// Создаёт 10 объектов Foo
v.resize(10);


📌 Совет:
Если не хочешь лишнего перемещения, используй emplace_back():


v.emplace_back(); // Вызывает конструктор Foo напрямую внутри вектора



@cpluspluc



tg-me.com/cpluspluc/1081
Create:
Last Update:

🧠 Задача с подвохом для продвинутых C++ разработчиков

🔹 Уровень: Advanced
🔹 Темы: std::vector, управление памятью, конструкторы/деструкторы, reserve() vs resize()

📌 Условие

Рассмотрим следующий код:


#include <iostream>
#include <vector>

struct Foo {
Foo() { std::cout << "Ctor\n"; }
~Foo() { std::cout << "Dtor\n"; }
Foo(const Foo&) { std::cout << "Copy\n"; }
Foo(Foo&&) noexcept { std::cout << "Move\n"; }
};

int main() {
std::vector<Foo> v;
v.reserve(3); // Резервируем место под 3 элемента

std::cout << "--- Pushing ---\n";
for (int i = 0; i < 3; ++i) {
v.push_back(Foo());
}

std::cout << "--- Done ---\n";
}


Вопросы

1. Что будет выведено на экран?
2. Почему reserve() не предотвращает конструкторы копирования/перемещения?
3. Что изменится, если заменить reserve(3) на resize(3)?

🔍 Разбор

Ожидаемый вывод:

--- Pushing ---
Ctor
Move
Dtor
Ctor
Move
Dtor
Ctor
Move
Dtor
--- Done ---
Dtor
Dtor
Dtor


🔧 Почему так происходит

- Foo() создаёт временный объект.
- push_back() вызывает перемещающий конструктор Move.
- Временный объект уничтожается (вызывается `Dtor`).
- reserve(3) выделяет память, но не создаёт объектов.

🔄 Если заменить `reserve(3)` на `resize(3)`

- resize(3) создаст 3 объекта Foo через конструктор по умолчанию.
- push_back(Foo()) добавит четвёртый, возможно вызовет realocation.
- Это может привести к копированию или перемещению уже созданных элементов.

⚠️ Подвох

Многие ошибочно считают, что reserve(n) создаёт n объектов. Но это не такreserve() только выделяет память, не вызывая конструкторы. Именно поэтому внутри push_back всё равно происходит перемещение или копирование.

🧠 Вывод

- reserve() — экономия на реаллокациях, без создания объектов.
- resize() — создаёт n объектов, вызывает конструкторы.
- Не путай эти методы — от этого зависит и производительность, и семантика.


// Резервирует память, не создаёт объекты
v.reserve(10);

// Создаёт 10 объектов Foo
v.resize(10);


📌 Совет:
Если не хочешь лишнего перемещения, используй emplace_back():


v.emplace_back(); // Вызывает конструктор Foo напрямую внутри вектора



@cpluspluc

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1081

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Find Channels On Telegram?

Telegram is an aspiring new messaging app that’s taking the world by storm. The app is free, fast, and claims to be one of the safest messengers around. It allows people to connect easily, without any boundaries.You can use channels on Telegram, which are similar to Facebook pages. If you’re wondering how to find channels on Telegram, you’re in the right place. Keep reading and you’ll find out how. Also, you’ll learn more about channels, creating channels yourself, and the difference between private and public Telegram channels.

Export WhatsApp stickers to Telegram on Android

From the Files app, scroll down to Internal storage, and tap on WhatsApp. Once you’re there, go to Media and then WhatsApp Stickers. Don’t be surprised if you find a large number of files in that folder—it holds your personal collection of stickers and every one you’ve ever received. Even the bad ones.Tap the three dots in the top right corner of your screen to Select all. If you want to trim the fat and grab only the best of the best, this is the perfect time to do so: choose the ones you want to export by long-pressing one file to activate selection mode, and then tapping on the rest. Once you’re done, hit the Share button (that “less than”-like symbol at the top of your screen). If you have a big collection—more than 500 stickers, for example—it’s possible that nothing will happen when you tap the Share button. Be patient—your phone’s just struggling with a heavy load.On the menu that pops from the bottom of the screen, choose Telegram, and then select the chat named Saved messages. This is a chat only you can see, and it will serve as your sticker bank. Unlike WhatsApp, Telegram doesn’t store your favorite stickers in a quick-access reservoir right beside the typing field, but you’ll be able to snatch them out of your Saved messages chat and forward them to any of your Telegram contacts. This also means you won’t have a quick way to save incoming stickers like you did on WhatsApp, so you’ll have to forward them from one chat to the other.

telegram from jp


Telegram C++ Academy
FROM USA