Joseph Kaptur
Joseph Kaptur

Reputation: 143

Calling clear on a vector immediately after construction?

I've seen some C++ code like this:

std::vector<int> vec;
vec.clear();
vec.push_back(42);

What is the purpose (if any) of clearing the vector right after creating it?

Upvotes: 5

Views: 154

Answers (1)

BeeOnRope
BeeOnRope

Reputation: 64925

It serves no purpose - the vector is already created in an empty state.

If you are lucky, your compiler will optimize away this redundant call entirely - recent versions of both gcc and clang do exactly that.

Upvotes: 7

Related Questions