LearnFrenzy
Sign in Take a free test

Move Semantics · Move Semantics Programs · Question 4

Efficient string concatenation with rvalue overloads in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links