Build a long report by chaining operator+ on std::string temporaries and compare with a version that reuses one buffer with += and reserve; show that the result is the same and how the temporary chain reuses storage.
Solution
main.cpp
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> parts{"name=Asha", "city=Pune", "course=C++", "level=pro"};
// a + b + c … : each + after the first gets an rvalue on the left, so it APPENDS to that temporary
std::string chained = parts[0] + ";" + parts[1] + ";" + parts[2] + ";" + parts[3];
// One buffer, reserved once
std::string built;
std::size_t total = parts.size() - 1;
for (const auto& p : parts) total += p.size();
built.reserve(total);
for (std::size_t i = 0; i < parts.size(); ++i) {
if (i) built += ';';
built += parts[i];
}
std::cout << chained << '\n' << (chained == built) << ' ' << built.size() << ' ' << (built.capacity() >= total) << '\n';
return 0;
}
Output Verified by compiling and running
name=Asha;city=Pune;course=C++;level=pro
1 40 1
std::string has operator+(std::string&&, …) overloads that append to the temporary and move it on, so a chain of + allocates far less than it seems. reserve() + += is the explicit way.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!