Search code examples
c++listconstructorgetlinepush-back

How to reduce the temp object when using push_back and getline?


I found an example about how to use std::getline(), and this is the code snippet:

std::istringstream input("abc|def|gh");
std::vector<std::array<char, 4>> v;

for (std::array<char, 4> a; input.getline(&a[0], 4, '|'); )
    v.push_back(a);

We can find that a is constructed at the for-loop, and it is passed into push_back as an argument. Is there a better way to make sure there is no temporary object like a to avoid overhead?

I have found a member function called emplace_back() to reduce the use of temporary object, but I am not sure how can I use it in this case, or I should just leave it for compiler optimizations?


Solution

  • getline needs to have a location to get the line in to, but you can make that location be the new element in the v vector, thus avoiding the use of an extra variable. Replace the for loop with a do/while loop:

    do {
        v.emplace_back();
    } while (input.getline(&v.back()[0], 4, '|'));
    v.pop_back();
    

    The emplace_back takes the place of a in your original code.