Openai/6957acb5-7d70-8002-a8e3-6e77a3f0799e
This conversation was exported from ChatGPT[1]
gpt-5-2-thinking edit
User: what will this program print? edit
what will this program print? I'm building with g++.
- include <vector>
- include <iostream>
struct A{
int i{};
A(int i_)
:i(i_)
{}
~A() {
std::cout << "Destruct " << i << std::endl;
}
};
int main() {
std::vector<A> vec; vec.reserve(5);
vec.emplace_back(1); vec.emplace_back(2);
}
Assistant: With vec.reserve5 there’s no reallocation, so no extra moves/copies/destructions happen during the emplacebacks. edit
With vec.reserve(5) there’s no reallocation, so no extra moves/copies/destructions happen during the emplace_backs. The only destructors run are when vec is destroyed at the end of main.
With g++ (libstdc++), the vector destructor destroys elements from begin() to end(), so you’ll get:
Destruct 1
Destruct 2
The C++ standard doesn’t require a specific destruction order for std::vector’s elements, so a different standard library could legally print the opposite order. en.cppreference.com[2]
References edit
- ↑ "Vector Destructor Behavior". ChatGPT. Retrieved 2026-01-03.
- ↑ "en.cppreference.com". en.cppreference.com. Retrieved 2026-01-03.