starcow
starcow

Reputation: 51

Check a vector before clear?

I'm not sure, but I think I've read that you should only delete a vector if it's not empty. So now I always check before I delete a vector:

if (!vector.empty()) {
    vector.clear();
}

However, I no longer find anything about whether this step is unnecessary.

Is it forbidden to use clear on an empty vector?

Upvotes: 3

Views: 331

Answers (2)

NutCracker
NutCracker

Reputation: 12263

Indeed, there was an issue related to the undefined behavior while clearing out an empty sequences or associative containers but this is fixed now and it is perfectly safe to call std::vector::clear without previously checking if the std::vector is empty.

Upvotes: 3

Jarod42
Jarod42

Reputation: 217293

The check is unneeded,

and decrease readability IMO.

Upvotes: 4

Related Questions