user4179247
user4179247

Reputation: 43

Why does outputting a vector's size cause allocations?

Take the following program:

const std::vector<std::vector<int>> v{10, std::vector<int>(10)};
std::cout << v.size() << std::endl;

By itself, only 12 allocations are made. If I add a loop:

for (auto e : v)
    std::cout << e.size() << " ";

22 allocations are made. Aren't the allocations made in advance?

Upvotes: 2

Views: 194

Answers (3)

Anton Savin
Anton Savin

Reputation: 41301

for (auto e : v) creates a copy of each container element causing allocations.

The reason for this is that auto resolves to std::vector<int>, that is e is taken by value.

To get rid of extra allocations use for (auto& e : v) or for (auto&& e : v).

You can also write for (const auto& e : v), but const here is redundant because v is constant.

Upvotes: 3

Jarod42
Jarod42

Reputation: 217135

with for (auto e : v), you make copy.

use for (const auto& e : v) instead.

Upvotes: 3

jrok
jrok

Reputation: 55395

Because you make a copy of a vector in each iteration. Try

for (const auto& e : v) // take a reference each iteration
    std::cout << e.size() << " "; 

and see the difference.

Upvotes: 6

Related Questions